Smooth user drawn lines in canvas

What you want is:

ctx.lineCap = 'round';

Here is an example of how it could be used:

Give it a try http://jsbin.com/ateho3

markup :

<canvas id="canvas"></canvas> 

JavaScript :

window.onload = function() {
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    var width  = window.innerWidth;
    var height = window.innerHeight;
    canvas.height = height;
    canvas.width = width;
    canvas.addEventListener('mousedown', function(e) {
      this.down = true;  
      this.X = e.pageX ;
      this.Y = e.pageY ;
      this.color = rgb();
    }, 0);
    canvas.addEventListener('mouseup', function() {
      this.down = false;      
    }, 0);
    canvas.addEventListener('mousemove', function(e) {
      this.style.cursor = 'pointer';
      if(this.down) {
          ctx.beginPath();
          ctx.moveTo(this.X, this.Y);
          ctx.lineCap = 'round';
           ctx.lineWidth = 3;
          ctx.lineTo(e.pageX , e.pageY );
          ctx.strokeStyle = this.color;
          ctx.stroke();

         this.X = e.pageX ;
         this.Y = e.pageY ;
      }
    }, 0);

    function rgb() {
      color = 'rgb(';
      for(var i = 0; i< 3; i++) {
        color += Math.floor(Math.random() * 255)+',';
      }
      return color.replace(/\,$/,')');
    }    
  };

I know that this is a 10 years old question but I think the answer is not complete. For a smooth line effect you need to set two properties to the canvas' context :

context.lineCap = 'round'
context.lineJoin = 'round'

The first one is for extremities of one path the second one is for corners of a path.

Some docs on lineJoin.
Some docs on lineCap.


I had to make a smooth canvas drawing for an mobile web application and learned couple of things. The Answer of Avinash is great but if you increase the line width, when you draw you will see broken lines. It is because the line cap is rectangular by default.

To make the line smoother you need to tweak something a bit.

ctx.lineCap = 'round';

this little tweak will give you a super smooth line.

To know more about this, try the following link

https://developer.mozilla.org/samples/canvas-tutorial/4_6_canvas_linecap.html


How about using Bezier curves?

Tags:

Html

Canvas