Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You need to build several abstraction layers to avoid major headache in your code.</p> <p>I just built a small 'Drawer' class which keep the user context, to remember what is he drawing, color, ... and the current list of all drawn things. Then you need some classes to store line, rect, ... data</p> <p>On each move of the mouse, the whole scene gets redrawn, which will works fast enough on most devices/browser i think.</p> <p><a href="http://jsfiddle.net/ZS34V/1/" rel="nofollow">http://jsfiddle.net/ZS34V/1/</a></p> <pre><code>var Drawer = function () { this.currentFigureType = 0 ; // 0 : free draw, 1 : line, // 2 : square, ... this.currentFigure = null ; this.figures = [] ; this.currentColor = 0 ; this.startX = 0 ; this.startY = 0 ; this.lastX = 0 ; this.lastY = 0 ; this.mouseDown = false; } Drawer.prototype.draw = function(ctx) { var figuresArray = this.figures; for (var i=0, len=figuresArray.length; i &lt; len; i++) { figuresArray[i].draw(ctx); } } </code></pre> <p>And now on the mouse up/down/move, we will check the context and act accordingly : start a new figure on mousedown, update it on mousemove, and store it on mouseup.</p> <pre><code>canvas.addEventListener('mousedown', function(e) { myDrawer.startX = e.pageX ; myDrawer.startY = e.pageY ; myDrawer.mouseDown = true ; switch (myDrawer.currentFigureType) { case 0 : break; case 1 : break ; } }, 0); canvas.addEventListener('mouseup', function() { myDrawer.mouseDown = false switch (myDrawer.currentFigureType) { case 0 : break; case 1 : var newLine = new Line(myDrawer.currentColor, myDrawer.startX, myDrawer.startY, myDrawer.lastX, myDrawer.lastY); myDrawer.figures.push(newLine); break ; } }, 0); canvas.addEventListener('mousemove', function(e) { if(!myDrawer.mouseDown) { return } myDrawer.lastX = e.pageX; myDrawer.lastY=e.pageY; ctx.clearRect(0,0,width, height); myDrawer.draw(ctx); switch (myDrawer.currentFigureType) { case 0 : // draw + store point break; case 1 : with(ctx) { console.log('we here'); beginPath(); moveTo(myDrawer.startX, myDrawer.startY); lineTo(e.pageX , e.pageY ); strokeStyle = myDrawer.currentColor; ctx.lineWidth=1; stroke(); } break; } }, 0); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload