简体   繁体   中英

browser doesn't display the image with canvas

i wrote this code but the browser refuse to display the pipe image from canvas. I need some help please.

 var cvs = document.getElementById("canvas"); var ctx = cvs.getContext("2d"); var chickenImage = new Image(); var pipe = new Image(); var jumpSound = new Audio(); chickenImage.src="asset/chicken.png"; pipe.src ="asset/pipe.png"; jumpSound.src ="asset/jump.wav"; function draw(){ ctx.drawImage(pipe,100,0); } draw(); 
 <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>chicken</title> </head> <body> <canvas id="canvas" width="288" height="512"></canvas> <script src="main.js"></script> </body> </html> 

You will need to wait for onload event, for the image to be loaded then you can draw her in the canvas.

pipe.onload = function () {
  ctx.drawImage(pipe, 0, 0);
};
pipe.src ="asset/pipe.png";

Or in your code you can use also:

pipe.onload = function () {
  draw();
};
pipe.src ="asset/pipe.png";

You need to wait until the image is loaded. The easiest way would be the .onload event which is run, when the image is finished loading and to use it just set it to your draw() function.

 var cvs = document.getElementById("canvas"); var ctx = cvs.getContext("2d"); var chickenImage = new Image(); var pipe = new Image(); var jumpSound = new Audio(); //chickenImage.src="asset/chicken.png"; pipe.src = "https://lorempixel.com/g/400/200/?random"; //jumpSound.src ="asset/jump.wav"; function draw() { ctx.drawImage(pipe, 100, 0); } pipe.onload = draw; 
 <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>chicken</title> </head> <body> <canvas id="canvas" width="288" height="512"></canvas> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM