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

时间:2018-06-16 21:15:56

标签: javascript html 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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

您需要等待onload事件,要加载图像,然后您可以在画布中绘制她。

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

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

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

答案 1 :(得分:0)

您需要等到图像加载完毕。最简单的方法是运行.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>