繁体   English   中英

浏览器不显示带有画布的图像

[英]browser doesn't display the image with canvas

我写了这段代码,但浏览器拒绝显示画布上的管道图像。 我需要一些帮助。

 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> 

您将需要等待onload事件,然后才能加载图像,然后才能在画布上绘制图像。

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

或者,您也可以在代码中使用:

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

您需要等待,直到图像被加载。 最简单的方法是运行.onload事件,当图像加载完成并要使用它时,只需将其设置为draw()函数即可。

 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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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