Category : Html | Author : Chtiwi Malek | First posted : 11/16/2012 | Updated : 9/26/2017
Tags : html5, canvas, draw, paint, code, snippet, clear, script
Draw on a HTML5 Canvas with a Mouse

Draw on a HTML5 Canvas with a Mouse

The HTML5's canvas element is the most important element that came up with the new html5, with canvas it is possible now to do image processing, drawing, saving, restoring layers, rendering graphs on the fly without the need for external plugins like Adobe's Flash player or silverlight.

In this tutorial I will write a small JavaScript code that will allow the user to freely write and paint on an html canvas, also I will add the ability to choose the line width and the color.

Here's how it looks like :


 Line width : Color :
First we need some Html code containing the canvas element, a select element with some line seizes, a select element to select the color and finally a button to clear the canvas.
<html>
<head></head>
<body onload="InitThis();">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="JsCode.js"></script>
    <div align="center">
        <canvas id="myCanvas" width="500" height="200" style="border:2px solid black"></canvas>
        <br /><br />
        <button onclick="javascript:clearArea();return false;">Clear Area</button>
        Line width : <select id="selWidth">
            <option value="1">1</option>
            <option value="3">3</option>
            <option value="5">5</option>
            <option value="7">7</option>
            <option value="9" selected="selected">9</option>
            <option value="11">11</option>
        </select>
        Color : <select id="selColor">
            <option value="black">black</option>
            <option value="blue" selected="selected">blue</option>
            <option value="red">red</option>
            <option value="green">green</option>
            <option value="yellow">yellow</option>
            <option value="gray">gray</option>
        </select>
    </div>
</body>
</html>

And now the javascript part, there's 3 functions here:

1 - InitThis() : this function will initiate the needed mouse events.
2 - Draw() : this will draw a line each time the mouse moves when pressed
3 - clearArea() : will clear the canvas to start drawing again.
var mousePressed = false;
var lastX, lastY;
var ctx;

function InitThis() {
    ctx = document.getElementById('myCanvas').getContext("2d");

    $('#myCanvas').mousedown(function (e) {
        mousePressed = true;
        Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, false);
    });

    $('#myCanvas').mousemove(function (e) {
        if (mousePressed) {
            Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true);
        }
    });

    $('#myCanvas').mouseup(function (e) {
        mousePressed = false;
    });
	    $('#myCanvas').mouseleave(function (e) {
        mousePressed = false;
    });
}

function Draw(x, y, isDown) {
    if (isDown) {
        ctx.beginPath();
        ctx.strokeStyle = $('#selColor').val();
        ctx.lineWidth = $('#selWidth').val();
        ctx.lineJoin = "round";
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(x, y);
        ctx.closePath();
        ctx.stroke();
    }
    lastX = x; lastY = y;
}
	
function clearArea() {
    // Use the identity matrix while clearing the canvas
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
If you want to upload and save the created image to the server checkout this tutorial :
Draw a Canvas image, Upload and save it on the server,
also I extended this tutorial to add Undo and Redo functions to the canvas.

Here's a live exemple you can play with on snippet.run :
 
A sample website to run and test this code is available in the attached file.

I'd love to hear your thoughts and ideas, so feel free to comment.
If you like this tutorial, please Share it.
About the author :
Malek Chtiwi is the man behind Codicode.com
34 years old full stack developer.
Loves technology; but also likes design, photography and composing music.
Comments & Opinions :
Great, thanks.
Thanks for creating and sharing this tutorial.
- by Joe on 2/4/2013
Awesome!
Really awesome illustration on HTML 5 mouse events.
- by iamvshlbndr on 4/29/2013
Web Developer
Spent an hour going through lousy tutorials....this one however rocks! Thank you so much!!!
- by Brian on 5/2/2013
Zoom and Rotate Canvas Painting
This looks nice, how could i implement Zooming and rotating the paintings in the same.
- by karthik on 10/5/2015
Canvas
I want to hide drawing lines until I submit the button

Scenerio: This is kind of test where want to check the ability to student where he/she moving mouse movement then stop the test then showing all drew lines
Is there any one help me please thanks in advance
- by Muhammad Yousuf Khan on 1/31/2019
How to save this as image
how to save this as image what we draw inside the canvas
- by MOHD SAQUIB on 4/15/2020
Touch from phone o tablet
What do I do to make it work with the touch of the phone or tablet?
- by Cristian Tamayo on 8/5/2020
Leave a Comment:
Name :
Email : * will not be shown
Title :
Comment :