May 7

Canvas Animations and Mouse Interactions

Canvas is a HTML5 tag/feature that is used to draw images, shapes and text with JavaScript. It enables animations or interaction of it's drawn elements, interactions can be triggered with the mouse or the keyboard.

Example of animations and interactions with the mouse movement:

In the example there are randomized circles animated which are connected with a line. When hovering the canvas with the mouse it creates a circle where the cursor is and connects the closest 2 circles with a line.

How to initalize canvas:

const canvas = document.querySelector("canvas");

// set the display size of the canvas.
const desiredWidthInCSSPixels = canvas.clientWidth;
const desiredHeightInCSSPixels = canvas.clientHeight;

canvas.style.width = desiredWidthInCSSPixels + "px";
canvas.style.height = desiredHeightInCSSPixels + "px";

// set the size of the drawingBuffer
// makes it look nice on retina screen
const devicePixelRatio = window.devicePixelRatio || 1;
canvas.width = desiredWidthInCSSPixels * devicePixelRatio;
canvas.height = desiredHeightInCSSPixels * devicePixelRatio;

const ctx = canvas.getContext('2d')

self.ctx.scale(devicePixelRatio, devicePixelRatio);

How to draw a circle:

ctx.beginPath();
// x-coordinate, y-coordinate, radius, start angle, end angle
ctx.arc(60, 50, 4, 0, 2 * Math.PI);
ctx.fillStyle = "#111";
ctx.fill();

Detect mouse movement on the canvas

canvas.addEventListener('mousemove', function(evt) {

    let rect = canvas.getBoundingClientRect();

    let mousePos = {
      x : evt.clientX - rect.left,
      y : evt.clientY - rect.top
    };
    // console log the x and y position of the mouse
    // relative to the canvas
    console.log(mousePos.x, mousePos.y);

}, false);

GET IN TOUCH