本文介绍了画布javascript drawImage方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
结果:不会将图像加载到画布.我正在获得白色矩形,知道为什么吗?我以为我可以直接从变量中调用draw方法,例如:bg.draw,或者这意味着我需要在画布上再次重新绘制Image并重新运行bg.draw?
Result : It doesn't load the image to the canvas. I'm getting white rectangle, any idea why? I thought I could just call the draw method directly from the variable , like e.g : bg.draw, or does that mean that I need to re-draw the Image again on the canvas and re-run the 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();`
下面是index.html:
Below is the index.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>
推荐答案
您需要等待图像加载后才能将其绘制到画布上.因此,将 bg.draw
包装在一个onload处理程序中:
You need to wait for the image to load before you can draw it to the canvas. So wrap bg.draw
in an onload handler:
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>
这篇关于画布javascript drawImage方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!