I’m attempting to get a square shape to follow my mouse around on the canvas using “mousemove”.
function start(){
var canvastmp = document.getElementById("myCanvas")
var canvas = canvastmp.getContext("2d");
window.addEventListener('mousemove', trevor, false);
}
function trevor(pos){
canvas.clearRect(0,0,600,400);
var x = pos.clientX;
var y = pos.clientY;
canvas.fillRect(x-25,y-25,100,100);
}
window.addEventListener('load',start,false);
When I run it, nothing at all shows up. I’ve been tweaking it and scouring it for a while now, and I can’t seem to figure out what’s wrong. Again, I’m sorry for the totally nooby question! Any help at all is much appreciated.
Also, I’m using Chrome, if that helps.
The problem is that
canvasis out of scope. To get it back in scope, either embed the trevor function inside thestartfunction, or pass the canvas context as a variable to a closure:Or alternatively, use a more object-like approach:
The nice thing about this is that the contexts are always relevant; trevor only knows the context it’s given, and the code that sets up the event handler also retrieves the context.