Responding to User Input Interactive Drawing with HTML5 Canvas & JavaScript

Responding to User Input

Draw a line on the canvas in response to user mouse movements code is below.

canvas.addEventListener(‘mousemove’, function(event) {

    const x = event.offsetX;

    const y = event.offsetY;

    ctx.lineTo(x, y);

    ctx.stroke();

});

Explanation:

An event listener for mousemove is added to the canvas. The offsetX and offsetY properties of the event provide the mouse’s position, which are used in lineTo() and stroke() to draw a line following the mouse movement.

Clearing the Canvas

To clear the entire canvas

ctx.clearRect(0, 0, canvas.width, canvas.height);

Explanation:

clearRect(x, y, width, height) clears the specified rectangular area and sets it to transparent black.  To clear the entire canvas, you can use the clearRect() method of the canvas’s 2D rendering context. This method clears the specified rectangular area, making it fully transparent. To clear the entire canvas, you specify a rectangle that covers the entire area of the canvas by starting at the top-left corner (0,0) and extending to the width and height of the canvas.

Here’s how you can do it:

var canvas = document.getElementById(‘myCanvas’);

var ctx = canvas.getContext(‘2d’);

// Clear the entire canvas

ctx.clearRect(0, 0, canvas.width, canvas.height);

In this code snippet:

  • canvas.width and canvas.height are used to specify the width and height of the canvas. This ensures that the rectangle you’re clearing matches the full dimensions of the canvas.
  • clearRect(0, 0, canvas.width, canvas.height) clears everything within the rectangle defined by the starting point (0,0) and the dimensions of the entire canvas.

Using clearRect() in this way effectively removes all drawings, colors, and styles previously applied to the canvas, resetting it to a completely transparent state. If your canvas has a default background color or image (set via CSS or other means), that background will become visible again after clearing the canvas.