[英]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. 您将需要等待onload
事件,然后才能加载图像,然后才能在画布上绘制图像。
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. 最简单的方法是运行.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.