[英]How do I fix my html/javascript code to animate a sprite sheet?
I attempted to animate a sprite sheet using html and javascript to no avail.我尝试使用 html 和 javascript 为精灵表制作动画,但无济于事。 Here is my sprite sheet
这是我的精灵表
Below is lines 36-59 of my code.下面是我的代码的第 36-59 行。 I'm not getting any errors so I don't really know what's wrong.
我没有收到任何错误,所以我真的不知道出了什么问题。 How do I fix/improve my code?
如何修复/改进我的代码?
This is for a project I'm doing.这是我正在做的一个项目。 I've tried using different methods I've found online but none really worked either.
我尝试过使用我在网上找到的不同方法,但都没有真正奏效。 I've tried shifting the image as well.
我也尝试过移动图像。
<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>
I expect the output to be an animation of a tree growing, but instead I'm getting a blank page.我希望输出是一棵树生长的动画,但我得到的是一个空白页面。
you should provide more code or a snippet, there are several variables didn't show up in your code你应该提供更多的代码或片段,有几个变量没有出现在你的代码中
and it's hard to debug your code if u use setInterval, you should make sure your code can work first.如果您使用 setInterval,则很难调试您的代码,您应该首先确保您的代码可以工作。
maybe you can try step by step:也许你可以一步一步地尝试:
draw()
function manually, check if the img draweddraw()
函数,检查 img 是否绘制setTimout(draw, 1000)
, check the resultsetTimout(draw, 1000)
,查看结果ok, and i think you can console.log
these variables in draw
好的,我想你可以在
draw
console.log
这些变量
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.