【发布时间】:2015-08-13 18:25:33
【问题描述】:
我一直在敲击键盘,试图弄清楚为什么this tutorial 的动画没有正确显示在画布上,如果有的话。在 chrome 中,它在画布上绘制图像的最左边部分,但在 safari 中,它什么也不画。
我尝试了不同的方法来延迟图像加载,将脚本标签放在 html 中的不同位置,但没有运气。在 chrome 中调试显示没有错误。
动画的源代码与他在教程中介绍的不太一样,我试图理解它。我已经做了两天了,你会在 30 秒内精确定位,我想看看这个该死的硬币旋转。
spriteSheet.jpg:
动画.html:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link href='http://fonts.googleapis.com/css?family=Ubuntu' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="style.css" type="text/css" />
<title>Test Profile Page</title>
</head>
<body>
<header>
<h1>Hello</h1>
</header>
<nav>
<ul>
<li><a href="index.html">Pictures</a></li>
<li><a href="animation.html">Animation?</a></li>
<li><a href="cartoon.html">Cartoon</a></li>
</ul>
</nav>
<section>
<img src="spriteSheet.jpg" />
<canvas id="coinAnimation"></canvas>
</section>
<footer>
</footer>
<script src="animation.js"></script>
</body>
</html>
动画.js:
window.onload = function () {
var spriteSheet = new Image();
spriteSheet.src = "spriteSheet.jpg";
//define sprite class
function sprite (options) {
var that = {},
frameIndex = 0,
tickCount = 0,
ticksPerFrame = options.ticksPerFrame || 0,
numberOfFrames = options.numberOfFrames || 1;
that.context = options.context;
that.width = options.width;
that.height = options.height;
that.image = options.image;
that.loop = options.loop;
that.update = function () {
tickCount += 1;
if (tickCount > ticksPerFrame) {
tickCount = 0;
// If the current frame index is in range
if (frameIndex < numberOfFrames - 1) {
// Go to the next frame
frameIndex += 1;
} else if (that.loop) {
frameIndex = 0;
}
}
};
that.render = function () {
// Clear the canvas
that.context.clearRect(0, 0, that.width, that.height);
// Draw the animation
that.context.drawImage(
that.image,
frameIndex * that.width / numberOfFrames,
0,
that.width / numberOfFrames,
that.height,
0,
0,
that.width / numberOfFrames,
that.height);
};
return that;
}
var canvas = document.getElementById("coinAnimation");
canvas.width = 100;
canvas.height = 100;
var coin = new sprite({
context: canvas.getContext("2d"),
width: 100,
height: 100,
image: spriteSheet
});
function gameLoop () {
window.requestAnimationFrame(gameLoop);
coin.update();
coin.render();
}
spriteSheet.addEventListener("load", gameLoop);
}
【问题讨论】:
标签: javascript html animation canvas