Canvas How to - Link mouse clicked points with lines








Question

We would like to know how to link mouse clicked points with lines.

Answer


<!--from  w  ww.j  a  va  2 s .  c om-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.9.1.js'></script>
<style type='text/css'>
canvas {
  border: 1px solid #000;
}
</style>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
var needFirstPoint = true;
function drawNextLine(ctx, x, y) {
    if (needFirstPoint) {
        ctx.lineWidth = 5;
        ctx.beginPath();
        ctx.moveTo(x, y);
        needFirstPoint = false;
    }
    else {
        ctx.lineTo(x, y);
        ctx.stroke();
    }
}
$(document).ready(function(){
    var canvas = $('#myCanvas').get(0);
    if (!canvas.getContext) { return; }
    var ctx = canvas.getContext('2d');
    $('#myCanvas').on('click', function(e){
        var offset = $(this).offset();
        var x = e.pageX - offset.left;
        var y = e.pageY - offset.top;
        drawNextLine(ctx, x, y);
    });
});
});//]]>  
</script>
</head>
<body>
  <canvas id="myCanvas" width="600" height="600"></canvas>
</body>
</html>

The code above is rendered as follows: