The problem is that canvas
is out of scope. To get it back in scope, either embed the trevor function inside the start
function, or pass the canvas context as a variable to a closure:
function start(){
var canvastmp = document.getElementById("myCanvas")
var ctx = canvastmp.getContext("2d");
window.addEventListener('mousemove', function(pos){trevor(ctx,pos)}, false);
}
function trevor(ctx, pos){
ctx.clearRect(0,0,600,400);
var x = pos.clientX;
var y = pos.clientY;
ctx.fillRect(x-25,y-25,100,100);
}
window.addEventListener('load',start,false);
Or alternatively, use a more object-like approach:
function trevor(ctx) {
function moveHandler(pos) {
ctx.clearRect(0,0,600,400);
ctx.fillRect(pos.clientX - 25, pos.clientY - 25, 100, 100);
}
}
var myTrevor = trevor((document.getElementById('myCanvas')).getContext('2d'));
window.addEventListener('load', myTrevor.moveHandler, false);
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.