简体   繁体   English

我无法在 html5 canvas 中使用 drawImage 方法绘制图像

[英]I Can't draw an image using drawImage method in html5 canvas

I am trying to create dino cloud game.我正在尝试创建恐龙云游戏。 but I encouter a problem.When I try to draw the image of the dinosaur in the canvas using drawImage method, the image is not drawn.但是我遇到了一个问题。当我尝试使用drawImage方法在canvas中绘制恐龙的图像时,图像没有绘制出来。 Can you help me please.你能帮我吗。

 const canvas = document.querySelector(".canvas"); canvas.height = 400; canvas.width = 800; const ctx = canvas.getContext("2d"); class Dino { constructor(x, y) { this.x = x; this.y = y; this.width = (88 * this.height) / 94; this.height = 70; } draw() { let image = new Image(); image.src = "imgs/player/idle/dino-idle-1.png"; ctx.drawImage(image, this.x, this.y, this.width, this.height); }} const dino = new Dino(20, 200); dino.draw();

I tried to draw dino using window.onload but it is not working我尝试使用 window.onload 绘制恐龙,但它不起作用

You need to draw an image on canvas only after the image is fully loaded (For example, using the onload trigger on the image).仅在图像完全加载后才需要在 canvas 上绘制图像(例如,在图像上使用onload触发器)。

Example below:下面的例子:

 const canvas = document.querySelector(".canvas"); canvas.height = 400; canvas.width = 800; const ctx = canvas.getContext("2d"); class Dino { constructor(x, y) { this.x = x; this.y = y; this.height = 70; this.width = (88 * this.height) / 94; } draw() { const image = new Image(); image.onload = () => ctx.drawImage(image, this.x, this.y, this.width, this.height); image.src = "https://www.fillmurray.com/600/400"; }} const dino = new Dino(20, 200); dino.draw();
 <canvas class="canvas"></canvas>

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

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