How do I hand draw on canvas with JavaScript?

Fabric.js

<!DOCTYPE html>
<html>
  <head>
    <title>Simple example</title>
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>
    <style type="text/css">
        #sheet {
            border:1px solid black;
        }
    </style>
    <script type="text/javascript">
        window.onload=function(){
            var canvas = new fabric.Canvas('sheet');
            canvas.isDrawingMode = true;
            canvas.freeDrawingBrush.width = 5;
            canvas.freeDrawingBrush.color = "#ff0000";
        }
    </script>
  </head>
  <body>
    <canvas id="sheet" width="400" height="400"></canvas>
  </body>
</html>

JSFiddle – Demo

  • The width of the lines can be controlled with canvas.freeDrawingBrush.width.
  • The color of the lines can be controlled with canvas.freeDrawingBrush.color.

This solution works with:

  • Desktop computers:
    • Chrome 33
    • Firefox 28
  • Touch devices:
    • Chrome 34 on Nexus 4
    • Opera 20 on Nexus 4
    • Firefox 28 on Nexus 4

Import / Export

Is only possible by serializing the complete canvas, see Tutorial

Line smoothing

Is done automatically and it seems not to be possible to deactivate it.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)