canvas{border:#666 1px solid;}

Canvas - javascript error

I have this code:

<!DOCTYPE html> <html> <head> <style type="text/css"> canvas{border:#666 1px solid;} </style> <script type="text/javascript"> var canvas = document.getElementById("canvas"), context = canvas.getContext("2d"), playerimage = new Image(), x = canvas.width / 2, //align to centre of the screen y = canvas.height / 2, //same as above speed = 5, //speed for the player to move at width = 50, //width of the player height = 50; //height of the player function init() { playerimage.src = "ninja.png"; //path to the image to use for the player canvas.addEventListener("keypress", update); } function update(event) { if (event.keyCode == 38) { y -= speed; //going up } if (event.keyCode == 40) { y += speed; //going down } if (event.keyCode == 37) { x -= speed; //going left } if (event.keyCode == 39) { x += speed; //going right } render(); } function render() { // context.clearRect(0, 0, canvas.width, canvas.height); context.drawImage(playerimage, x, y, width, height); } </script> </head> <body onload="init();"> <button onclick="init();">Draw</button> <canvas id="Mycanvas" width="550" height="400"></canvas> </body> </html> 

javascript console always gives me canvas - null error

+4
source share
2 answers

There are two problems with the following line of code:

 var canvas = document.getElementById("canvas"), 
  • Run before the canvas element has been parsed and added to the DOM.
  • It uses an invalid identifier.

Change it to:

 var canvas = document.getElementById("Mycanvas"), 

... and move the entire <script> block to the end of the body, immediately before </body> .

+14
source

Your html canvas id does not match the one you use in

 var canvas=document.getElementById("canvas"); 

The correct HTML should be:

 <canvas id="canvas" width="550" height="400"></canvas> 
+2
source

Source: https://habr.com/ru/post/1493661/


All Articles