CHANNELS:

All
n
nst1 posted 2 years ago
n
nst1 posted 2 years ago
var canvas = document.querySelector('canvas');

//set canvas size

canvas.width = window.innerWidth;
canvas.height = window.innerHeight / 1.9;

//add drawing context
var c = canvas.getContext('2d');



var mouse = {
x: undefined,
y: undefined
}
0
chris posted 2 years ago

So when nesting your canvas inside of other elements, you'll need to take into consideration the new position of the canvas.

Mouse coordinates here are relative to the window, but if your canvas is offset from the window, well, the mouse coordinates aren't going to correlate correctly.

To fix this, you'll want to get the canvas' offset relative to the window. You can do so by subtracting the canvas' top and left positions from your mouse's x and y coordinates.

Check out how I did it here within one of my canvas pieces:

function mousemove(e) {
  mouse.x =
    e.clientX -
    document.querySelector('canvas').getBoundingClientRect().left
  mouse.y =
    e.clientY - document.querySelector('canvas').getBoundingClientRect().top
},

0

Want to participate?

Create a free Chris Courses account to begin

or
Sign In

Providing the lift to launch your development career

© 2022 Chris Courses. All rights reserved.