Canvas How to - Handle mouse up event








Question

We would like to know how to handle mouse up event.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script type='text/javascript'>
$(window).load(function(){<!--from w ww .  j av  a2 s . com-->
    document.onselectstart = function(){ return false; };
    var x = 0;
    var y = 0;
    function draw(x,y,w,r,g,b,a){
        ctx.lineWidth = w;
        ctx.lineTo(x, y);
        ctx.strokeStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
        ctx.stroke()
    };
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var w = 10;
    var drawing = false;
    $('canvas').mousedown(function(){
        drawing = true;
        ctx.beginPath();
    });
    $('canvas').mouseup(function(){
        drawing = false;
        ctx.closePath();
    });
    $('canvas').mousemove(function(e){
        if(drawing == true){
            x = e.pageX;
            y = e.pageY;
            draw(x,y,w +10,0,0,0,0.1);
            draw(x,y,w,100,100,100,1);
        };
    });
});
</script>
</head>
<body>
  <canvas id="canvas" width="400" height="300"
    style="border: 1px #000 solid;"></canvas>
</body>
</html>

The code above is rendered as follows: