-2

The code I am using is supposed to make an image, square.png, move to the cursor. However, the code cannot run.

I've tried to look for typos and errors in my code.

var canvas = document.createElement('canvas');
canvas.width = 800;
canvas.height = 600;
document.body.appendChild(canvas);

document.addEventListener('mousemove',function(event){

    var similarX = event.clientX;
    var similarY = event.clientY;
    document.getElementById('body').innerHTML = "x:" + similarX + ", y:" + similarY;
})
var square = new Image();
square.src = 'square.png';

window.addEventListener('load' , start);

var c = canvas.getContext('2d');
function start() {
    c.fillStyle = 'green';
    c.fillRect = 10, 10, 30, 30;
    c.drawImage(square,similarX , similarY);

    window.requestAnimationFrame(start)
}
document.body.appendChild(canvas);

this is from between the script tags in an html document.

The square is supposed to be drawn at where the mouse pointer is, but according to Chrome dev tools, the variables similarX and similarY are not recognized in the function "load".

Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
  • What does that mean, “not recognized”? Give us the concrete error message or misbehavior. – deceze Jul 17 '19 at 22:29
  • 1
    because the variables are defined inside of the mousemove and the fact they are not going to update in the start method after it runs. Learn about `var` and scope – epascarello Jul 17 '19 at 22:30

1 Answers1

0

As @eepascarello said, you are trying to access variables out of scope. You can move the similarX and similarY variables out of the scope of the mousemove event

var canvas = document.createElement('canvas');
canvas.width = 800;
canvas.height = 600;
document.body.appendChild(canvas);

//possible you want to set these to something besides 0
var similarX = 0;
var similarY = 0;

document.addEventListener('mousemove',function(event){

    similarX = event.clientX;
    similarY = event.clientY;
    document.getElementById('body').innerHTML = "x:" + similarX + ", y:" + similarY;
})
var square = new Image();
square.src = 'square.png';

window.addEventListener('load' , start);

var c = canvas.getContext('2d');
function start() {
    c.fillStyle = 'green';
    c.fillRect = 10, 10, 30, 30;
    c.drawImage(square,similarX , similarY);

    window.requestAnimationFrame(start)
}
document.body.appendChild(canvas);

Notice, this wont give you the functionality to relocate the rectangle on mousemove, but it will give you the ability to load without errors. To update on mousemove, you will probably need to do something such as call start() at the end of your mousemove event;

Seth McClaine
  • 9,142
  • 6
  • 38
  • 64