[英]How would I animate a sprite to flash 2 different colors on screen in JavaScript, with this code? Or rather how would I fix it?
[英]How do I fix my html/javascript code to animate a sprite sheet?
我嘗試使用 html 和 javascript 為精靈表制作動畫,但無濟於事。 這是我的精靈表
下面是我的代碼的第 36-59 行。 我沒有收到任何錯誤,所以我真的不知道出了什么問題。 如何修復/改進我的代碼?
這是我正在做的一個項目。 我嘗試過使用我在網上找到的不同方法,但都沒有真正奏效。 我也嘗試過移動圖像。
<html>
<head>
<title>Tree Animation</title>
</head>
<body>
<canvas id='canvas'></canvas>
<script>
var canWidth = 400;
var canHeight = 100;
//position where the frame will be drawn
var x = 0;
var y = 0;
var srcX;
var srcY;
var sheetWidth = 230;
var sheetHeight = 79;
var frameCount = 5;
var width = sheetWidth/frameCount;
var height;
var currentFrame = 0;
var tree = new Image();
tree.src = "tree sprite.jpg"
var canvas = document.getElementById('canvas');
canvas.width = canWidth;
canvas.height = canHeight;
var ctx = canvas.getContext('2d');
function updateFrame(){
currentFrame = ++currentFrame%frameCount
srcX = currentFrame*width;
srcY = 0;
ctx.clearRect(x, y, width, height);
}
function draw(){
updateFrame();
}
setInterval(function(){
draw();
}, 100);
</script>
</body>
</html>
我希望輸出是一棵樹生長的動畫,但我得到的是一個空白頁面。
你應該提供更多的代碼或片段,有幾個變量沒有出現在你的代碼中
如果您使用 setInterval,則很難調試您的代碼,您應該首先確保您的代碼可以工作。
也許你可以一步一步地嘗試:
draw()
函數,檢查 img 是否繪制setTimout(draw, 1000)
,查看結果好的,我想你可以在draw
console.log
這些變量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.