implement sketch brush - Javascript Canvas

Javascript examples for Canvas:Example

Description

implement sketch brush

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.js"></script> 
      <script type="text/javascript">
    $(window).load(function(){/*  w  ww  . j a  va  2 s  .  c  o m*/
var mousemovements = [];
$(document).on("mousemove", function(event)
{
  if (mousemovements.length > 20)
  {
     mousemovements.pop();
  }
  for(var i = mousemovements.length-1 ; i >=0 ; i--)
  {
     var movement = mousemovements[i];
     var middlemovement = mousemovements[Math.round(i/2)];
     drawBeziercurveFromTo(movement.mouseX, movement.mouseY,
                           event.pageX, event.pageY,
                          middlemovement.mouseX, middlemovement.mouseY);
  }
  mousemovements.unshift({ mouseX:event.pageX, mouseY:event.pageY });
});
function drawBeziercurveFromTo(x1, y1, x2, y2, cpx, cpy)
{
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext('2d');
    context.strokeStyle = "rgba(50,50,50,.01)";
    context.lineWidth = 2;
    cpx1 = cpx2 = cpx; // Here you can add a fancier bezier calculation
    cpy1 = cpy2 = cpy; // Right now it's basically just a lineto.
    context.beginPath();
    context.moveTo(x1, y1);
    context.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x2, y2);
    context.lineTo(x2, y2);
    context.stroke();
}
    });

      </script> 
   </head> 
   <body> 
      <canvas width="600" height="600" id="myCanvas">  
      </canvas>
   </body>
</html>

Related Tutorials