I am not able to draw shapes except for random lines onthe canvas. What will be the code for other options eg any line, rectangle or a triangle?
<script type="text/javascript">
var canvas, context, tool, e;
var varblurup=0;
var varsizeup=1;
var swtchclr;
// Keep everything in anonymous function, called on window load.
if(window.addEventListener) {
window.addEventListener('load', function () {
//check tool is pen or line or shape
var chktool="pen";
function init () {
alert("Line3");
// Find the canvas element.
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
//varblurup=10;
context.shadowColor = 'colour';
context.shadowBlur = 0;
context.lineWidth=1;
context.lineJoin = 'miter';
context.miterLimit = 4;
this.context.save();
// Pencil tool instance.
//tool = new tool_pencil();
//alert("Pen");
if(chktool=="pen")
{ tool = new tool_pencil();
alert("Pen");
}else if (chktool=="line")
{
tool2 = new tool_line();
alert("Line");
}
// Attach the mousedown, mousemove and mouseup event listeners.
canvas.addEventListener('mousedown', ev_canvas, false);
canvas.addEventListener('mousemove', ev_canvas, false);
canvas.addEventListener('mouseup', ev_canvas, false);
}
// This painting tool works like a drawing pencil which tracks the mouse
// movements.
function tool_pencil () {
var tool = this;
this.started = false;
// This is called when you start holding down the mouse button.
开发者_开发技巧 // This starts the pencil drawing.
this.mousedown = function (ev) {
context.beginPath();
context.moveTo(ev._x, ev._y);
tool.started = true;
};
// This function is called every time you move the mouse. Obviously, it only
// draws if the tool.started state is set to true (when you are holding down
// the mouse button).
this.mousemove = function (ev) {
if (tool.started) {
context.lineTo(ev._x, ev._y);
//this.style('stroke-opacity').value
context.stroke();
}
};
// This is called when you release the mouse button.
this.mouseup = function (ev) {
if (tool.started) {
tool.mousemove(ev);
tool.started = false;
}
};
}
// The general-purpose event handler. This function just determines the mouse
// position relative to the canvas element.
function ev_canvas (ev) {
if (ev.layerX || ev.layerX == 0) { // Firefox
ev._x = ev.layerX;
ev._y = ev.layerY;
} else if (ev.offsetX || ev.offsetX == 0) { // Opera
ev._x = ev.offsetX;
ev._y = ev.offsetY;
}
// Call the event handler of the tool.
var func = tool[ev.type];
if (func) {
func(ev);
}
}
init();
}, false); }
I found the Mozilla canvas tutorial to be a helpful guide. It covers most areas including shape drawing:
https://developer.mozilla.org/en/Canvas_tutorial
https://developer.mozilla.org/en/Canvas_tutorial/Drawing_shapes
It is quite an extended question so here are a couple of links about it..
HTML5 Canvas: Shape Drawing
A Quick Introduction to the HTML 5 Canvas
A Quick Introduction to the HTML 5 Canvas – Part Two
精彩评论