[英]Drawn image not moving on canvas
我用 html canvas 制作游戲。我需要移動圖像精靈,但我的代碼只在同一個 position 上重繪圖像。哪里有問題?代碼在這里
class Duck{
constructor(x,y){
this.x = x;
this.y = y;
this.skin = 'img/path/';
}
draw() {
var img = new Image();
img.src = this.skin;
img.onload = function () {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img,this.x, this.y);
ctx.restore();
}
}
move(){
this.x+=10;
this.y+=10;
}
}
var canvas = document.getElementById("canv");
var ctx = canvas.getContext("2d");
var d = new Duck(0,0);
//this function called from another file and it works
function mainLoop() {
d.move();
d.draw();
requestAnimationFrame(mainLoop);
}
這是您修復的代碼:
ctx.restore();
this
上下文存儲在draw
方法中,以供img.onload
回調中參考 class Duck { constructor(x, y) { this.x = x; this.y = y; this.skin = 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iaXNvLTg4NTktMSI/+DQoJPHBhdGggc3R5bGU9ImZpbGw6I0ZGQjY0MTsiIGQ9Ik00OS41MzksMjc5Ljc5NmMyLjEzNy0xNC4zMTcsMTEuNjE4LTI1Ljk0MiwyNC4yODItMzEuMjQ1Yy00Ljg2Ni0yLjAyMi0xMC4wOTEtMy4xMS0xNS40MTItMy4xMQ0KCQlsMCwwYy0xOS45NDcsMC0zNi44MzMsMTQuNjI4LTM5Ljc3NiwzNC4zNTdDNy44ODksMzUxLjgxNiw2LjUyLDUxMiwyMDYuOTY2LDUxMmgzMC45MDVDMzcuNDI1LDUxMiwzOC43OTQsMzUxLjgxNiw0OS41MzksMjc5Ljc5NnoNCgkJIi8++DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPGc+DQo8L2c+DQo8Zz4NCjwvZz4NCjxnPg0KPC9nPg0KPC9zdmc+DQo='; } draw() { var img = new Image(); img.src = this.skin; const that = this; img.onload = function () { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(img, that.x, that.y); } } move() { this.x += 10; this.y += 10; } } var canvas = document.getElementById("canv"); var ctx = canvas.getContext("2d"); var d = new Duck(0, 0); //this function called from another file and it works function mainLoop() { d.move(); d.draw(); requestAnimationFrame(mainLoop); } mainLoop();
<canvas id="canv" height="600px" width="600px"></canvas>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.