CHANNELS:

All
n
Broken Canvas
Canvas
nst1 posted 25 days ago

Hi Chris, we are having a little bit of trouble here. The canvas and mouse pointers all seem to brake when we add the <canvas> tag within a div element.

<div class="position-relative py-6 py-lg-10">

<div class="bg-holder rounded-soft overlay" style="background-image:url(assets/img/gallery/ai.jpg);">

<canvas></canvas> </div> <!--/.bg-holder-->

<div class="position-relative text-center"></div>

</div>

n
nst1 posted 25 days 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 22 days 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
Cheat Sheet Preview

Download The Official Chris Courses HTML5 Canvas Cheat Sheet

Essential canvas syntax at your fingertips.

Download Now

Providing the lift to launch your development career

© 2020 Chris Courses. All rights reserved.