I have a web application where you can draw a rectangle on a canvas. I use two canvas elements: one for the preview while drawing and another one laying exactly under the ot
Problem
You are drawing rectangles with context2.rect
which is a path command.
Path commands are "remembered" by the canvas until a new context2.beginPath
is issued
Therefore, all your previous rects are being remembered and redrawn when you do context2.stroke
Fix
Just put context2.beginPath in your mousemove event handler: http://jsfiddle.net/m1erickson/A8ge6/
canvas2.addEventListener("mousedown",startLine);
canvas2.addEventListener("mouseup",drawLine);
canvas2.addEventListener('mousemove', function (evt) {
var rect = canvas2.getBoundingClientRect();
x = evt.clientX - rect.left;
y = evt.clientY - rect.top;
if (clicked) {
canvas2.width = canvas2.width;
console.log(xStart);
// add beginPath so previous context2.rect's are dismissed
context2.beginPath();
context2.rect(xStart, yStart, x - xStart, y - yStart);
context2.stroke();
}
}, false);
If you only need to stroke a rectangle you can use this version:
context2.strokeRect(xStart, yStart, x - xStart, y - yStart);
instead of rect()
+ stroke()
.
This does not add any sub path to the main path but draws directly to canvas. If you need to add other shapes to your path later remember to use beginPath()
for rect()
in a similar way as you already do in startLine()
as rect()
add a sub-path.
There is Nothing Wrong with the Code and nothing Wrong With IE 9,What you missed is a l'le concept ,
addEventListener() didn't work For IE instead you have to use attachEvent() for it to make your Code run in IE
//For your code to work in IE
if (!canvas2.addEventListener) {
canvas2.attachEvent("onclick", CanvasFunction);
}
//for rest of the Browser
else {
canvas2.addEventListener("click", CanvasFunction, false);
}
function CanvasFunction(evt)
{
var rect = canvas2.getBoundingClientRect();
x = evt.clientX - rect.left;
y = evt.clientY - rect.top;
if (clicked) {
canvas2.width = canvas2.width;
console.log(xStart);
// add beginPath so previous context2.rect's are dismissed
context2.beginPath();
context2.rect(xStart, yStart, x - xStart, y - yStart);
context2.stroke();
}
}
Playing with Canvas ,remember IE doesn't support addEventListners ..Enjoy Coding