Mouse drawing in HTML

So far we’ve looked at mostly static graphics on canvas. But we can also create shapes dynamically by simply drawing with the mouse pointer.

To do this, define the following page:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canvas in HTML5</title>
</head>

<body>
    <canvas id="myCanvas" width="350" height="250" style="background-color:#eee; border: 1px solid #ccc; margin:10px;">
        Your browser does not support Canvas
    </canvas>
    <script>
        var canvas = document.getElementById("myCanvas"),
            context = canvas.getContext("2d"),
            w = canvas.width,
            h = canvas.height;

        var mouse = { x: 0, y: 0 };
        var draw = false;

        canvas.addEventListener("mousedown", function (e) {

            mouse.x = e.pageX - this.offsetLeft;
            mouse.y = e.pageY - this.offsetTop;
            draw = true;
            context.beginPath();
            context.moveTo(mouse.x, mouse.y);
        });
        canvas.addEventListener("mousemove", function (e) {

            if (draw == true) {

                mouse.x = e.pageX - this.offsetLeft;
                mouse.y = e.pageY - this.offsetTop;
                context.lineTo(mouse.x, mouse.y);
                context.stroke();
            }
        });
        canvas.addEventListener("mouseup", function (e) {

            mouse.x = e.pageX - this.offsetLeft;
            mouse.y = e.pageY - this.offsetTop;
            context.lineTo(mouse.x, mouse.y);
            context.stroke();
            context.closePath();
            draw = false;
        });
    </script>
</body>

</html>
 


Three handlers are defined for handling mouse movement on the canvas element – mouse down, mouse move, and mouse release. When the mouse is pressed, we set the draw variable to true. That is, drawing is in progress. Also, when you click, we fix the point from which the drawing will go.

When moving the mouse, we get the point to which the pointer has moved, and draw a line. When the pointer is released, we close the graphics path with the method context.closePath()and reset the draw variable to false.