css - Javascript: Drawing rectangle on canvas doesn't work on IE -
i have web application can draw rectangle on canvas. use 2 canvas elements: 1 preview while drawing , 1 laying under other 1 drawing it.
the problem have in internet explorer, canvas2.width = canvas2.width
doesn't clear content of canvas2, necessary because every mousemove rectangle gets drawn again. tried context2.clearrect(0,0,canvas2.width,canvas2.height)
, but, however, preview rectangle doesn't drawn @ all. try out on http://jsfiddle.net/y389a/2/
html:
<canvas id="canvas" width="600" height="400"></canvas> <canvas id="canvas2" width="600" height="400" onmouseup="return drawline()" onmousedown="return startline()"></canvas>
css:
#canvas, #canvas2 { position:absolute; left:0px; top:0px; border-width:1px; border-style:solid; border-color:#666666; cursor:default !important; }
javascript:
var x; var xstart; var y; var ystart; var clicked = false; var canvas = document.getelementbyid("canvas"); var context = canvas.getcontext("2d"); var canvas2 = document.getelementbyid("canvas2"); var context2 = canvas2.getcontext("2d"); context.strokestyle = "black"; context.linecap = "round"; 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; context2.rect(xstart, ystart, x - xstart, y - ystart); context2.stroke(); } }, false); function startline() { context.beginpath(); xstart = x; ystart = y; clicked = true; } function drawline() { clicked = false; context.rect(xstart, ystart, x - xstart, y - ystart); context.stroke(); }
problem
you drawing rectangles context2.rect
path command.
path commands "remembered" canvas until new context2.beginpath
issued
therefore, previous rects being remembered , redrawn when context2.stroke
fix
just put context2.beginpath in 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 previous context2.rect's dismissed context2.beginpath(); context2.rect(xstart, ystart, x - xstart, y - ystart); context2.stroke(); } }, false);
Comments
Post a Comment