Canvas How to - Drag and move to draw








Question

We would like to know how to drag and move to draw.

Answer


<!--  w w w.  j a  v a 2s .co  m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.5.2.js'></script>
<style type='text/css'>
canvas{border:1px solid black}
</style>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
    var ctx = $('canvas').get(0).getContext('2d');
    $('canvas').mousedown(function(e) {
        ctx.beginPath();
        ctx.moveTo(e.offsetX, e.offsetY);
    });
    $('canvas').mouseup(function(e) {
        ctx.lineTo(e.offsetX, e.offsetY);
        ctx.stroke();
    });
});//]]>  
</script>
</head>
<body>
  <p>drag and move to draw</p>
  <canvas></canvas>
</body>
</html>

The code above is rendered as follows: