[英]Canvas javascript drawImage method
Result: It doesn't load the image to the canvas.结果:它不会将图像加载到 canvas。 I'm getting white rectangle, any idea why?
我得到白色矩形,知道为什么吗? I thought I could just call the draw method directly from the variable, like eg: bg.draw, or does that mean that I need to re-draw the Image again on the canvas and re-run the bg.draw?
我想我可以直接从变量中调用draw方法,例如:bg.draw,或者这是否意味着我需要在canvas上再次重新绘制图像并重新运行bg.draw?
const cvs = document.getElementById("firstplatform");
const ctx = cvs.getContext("2d");
// GAME VARS AND CONSTS
let frames = 0;
// LOAD IMAGE
const sprite = new Image();
sprite.src = "img/sprite.png";
//BACKGROUND
const bg = {
sX: 0,
sY: 0,
w: 275,
h: 226,
x: 0,
y: cvs.height - 226,
draw: function () {
ctx.drawImage(
sprite,
this.sX,
this.sY,
this.w,
this.h,
this.x,
this.y,
this.w,
this.h
);
ctx.drawImage(
sprite,
this.sX,
this.sY,
this.w,
this.h,
this.x + this.w,
this.y,
this.w,
this.h
);
},
};
// DRAW
bg.draw();`
Below is the index.html:下面是索引html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>First Game</title>
<link href="https://fonts.googleapis.com/css?family=Teko:700" rel="stylesheet">
<style>
canvas{
border: 1px solid #000;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="firstplatform" width="320" height="480"></canvas>
<script src="game.js"></script>
</body>
</html>
You need to wait for the image to load before you can draw it to the canvas.您需要等待图像加载,然后才能将其绘制到 canvas。 So wrap
bg.draw
in an onload handler:所以将
bg.draw
包装在 onload 处理程序中:
sprite.onload = function()
{
bg.draw();
}
const cvs = document.getElementById("firstplatform"); const ctx = cvs.getContext("2d"); // GAME VARS AND CONSTS let frames = 0; // LOAD IMAGE const sprite = new Image(); sprite.src = "https://cdn.sstatic.net/Img/unified/sprites.svg?v=fcc0ea44ba27"; //BACKGROUND const bg = { sX: 0, sY: 0, w: 275, h: 226, x: 0, y: cvs.height - 226, draw: function () { ctx.drawImage( sprite, this.sX, this.sY, this.w, this.h, this.x, this.y, this.w, this.h ); ctx.drawImage( sprite, this.sX, this.sY, this.w, this.h, this.x + this.w, this.y, this.w, this.h ); }, }; sprite.onload = function() { bg.draw(); }
<canvas id="firstplatform" width="320" height="480"></canvas>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.