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.
<body onload="InitThis();">
    <script src="//" 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>
        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>

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.strokeStyle = $('#selColor').val();
        ctx.lineWidth = $('#selWidth').val();
        ctx.lineJoin = "round";
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(x, y);
    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 :
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
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
hello bro, i download the attached file but when i open it using the attached file i cannot use the paint function.. i did not do any changes on the code to...can you help me with this.. since this website is working i wonder what the problem with the code..

- by Faizal on 3/14/2013


<script src="//   change to: 

<script src="


- by Maciek on 4/3/2013
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
This is a great tutorial! Thanks for posting this, I was looking for something like this. Anyone know the license on it?
- by Bob on 5/13/2013
best tutorial, however.........
however when I start to draw , the canvas gets selected ... this is really bad..
- by Ali on 7/5/2013
paint not working
Hello brother ! I downloaded your attachement code for painting.. It is not working when I open your attachement file in my client machine.. 

What should I do next level.. Please share me...

Thanks an advance,

- by manivannan on 12/24/2014
Nice Work
How would I go about creating more than one canvas that I can draw in, that is completely independant of the other?
- by trevelle on 2/17/2015
well done
It is a great job. I really like it. however, it can not work independant of internet.can you please tell us how it can work of line.
- by Elhaytham on 4/11/2015
How to save and load the drawing
how we can save and reload the drawing?
- by Zahid on 4/16/2015
What shall i do?
Your code doesn't run in my browser.
My browser is latest version of chorme.
- by Susan on 4/16/2015
This is what I have been looking for.. for some time ... grat work.
Is it possible to load astatic image and do the drawing on that


- by Ranil on 4/19/2015
and touch?
- by CHARLES on 5/20/2015
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
looks dot by dot
I have a similar code in your example it draws quite fast but in my code if i am too fast it is dot by dot
why can that be
- by nikos on 10/13/2015
looks dot by dot
I have a similar code in your example it draws quite fast but in my code if i am too fast it is dot by dot
why can that be
- by nikos on 10/13/2015
Draw on Image
How can we apply drawing on Image
- by Developer on 10/25/2015
delete text draw in canvas
Sorry, i want ask. How to delete text draw in canvas.... thanks
- by andrisemangat on 10/26/2015
thanks alot
- by ishi on 12/23/2015
Is there a way to make it work on ipads?
- by Michael on 6/29/2016
Nice,it works
- by One inch punch on 10/5/2017
How i can save drawing in database
How i can  save drawing in database ? 
Please added a Save button 
- by Umesh on 5/21/2018
Just wanted to say Hello!
gout medscape m 31 pill nizoral cream over the counter carbidopa-levodopa 25-100 Hi to every one, the contents existing at this web site are actually remarkable for people knowledge, well, keep up the good work fellows. is plavix a blood thinner
- by Pedro on 6/8/2018
How i can touch on android device?
can u help me for android device? Touchscreen device
- by Ardias on 6/11/2018
Leave a Comment:
Name :
Email : * will not be shown
Title :
Comment :