Skip to content Skip to sidebar Skip to footer

Drawing On Mouse Move With Canvas, HMTL5?

What I am trying to achieve is a simple functionality to draw lines on a canvas when the mouse is clicked. I have looked at code online and am trying to implement it myself but it

Solution 1:

Well at a cursory glance you are missing a ">" at the end of line #2.


Solution 2:

A couple of issues:

  • Adjust your mouse positions by the offset of the canvas (unless your canvas is at top-left of the browser)

  • do all drawing commands in mousemove (otherwise you will restroke the line with every ctx.stroke)

Here's example code and a Demo: http://jsfiddle.net/m1erickson/kkLrT/

<!doctype html>
<html>
<head>
<link  type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>
<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var BB=canvas.getBoundingClientRect();
    var offsetX=BB.left;
    var offsetY=BB.top;

    var lastX,lastY;
    var isDown=false;

    canvas.onmousedown=handleMousedown;
    canvas.onmousemove=handleMousemove;
    canvas.onmouseup=handleMouseup;


    function handleMousedown(e){
         e.preventDefault();
         e.stopPropagation();
         lastX=e.clientX-offsetX;
         lastY=e.clientY-offsetY;
         isDown=true;
    }

    function handleMouseup(e){
         e.preventDefault();
         e.stopPropagation();
         isDown=false;
    }

    function handleMousemove(e){
         e.preventDefault();
         e.stopPropagation();

         if(!isDown){return;}

         var mouseX=e.clientX-offsetX;
         var mouseY=e.clientY-offsetY;

         ctx.beginPath();
         ctx.moveTo(lastX,lastY);
         ctx.lineTo(mouseX,mouseY);
         ctx.stroke();

         lastX=mouseX;
         lastY=mouseY;
    }


}); // end $(function(){});
</script>
</head>
<body>
    <h4>Drag mouse to draw.</h4>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

Post a Comment for "Drawing On Mouse Move With Canvas, HMTL5?"