【发布时间】:2018-07-28 09:47:41
【问题描述】:
我一直在为动画和间隔/fps 的想法而苦恼。我了解此 sn-p 中代码的工作原理,但我只是不明白如何在减慢动画速度的同时仍将画布保持在 60 fps 刷新率。
$(document).ready(function(){
startAnimating(60);
});
//Global Variables
var fpsInterval;
var then;
var shift = 0;
var frameWidth = 107;
var frameHeight = 140;
var canvasX = 0;
var canvasY = 0;
var myImage = new Image();
var totalFrames = 8;
var currentFrame = 0;
//Loading image
myImage.src = "https://i.imgur.com/N3shTgD.png";
myImage.addEventListener("load", loadImage, false);
//Function to begin animation with set fps
function startAnimating(fps)
{
fpsInterval = 1000/fps;
then = Date.now();
animate();
}
function animate() {
var now = Date.now();
var elapsed = now - then;
if (elapsed > fpsInterval)
{
then = now - (elapsed % fpsInterval);
var cvs = $("canvas").get(0);
var ctx = cvs.getContext("2d");
//clear background
ctx.clearRect(0, 0, cvs.width, cvs.height);
//draw each frame and place in middle of canvas
/*
drawImage(
"Image object",
"X coordinate next sprite in png (Location of sprite?)",
"Y coorinate next sprite in png",
"Width of sprite in png (How big is sprite?)",
"Height of sprite in png"
"X coordinate on canvas (Where to draw it?)"
"Y coordinate on canvas"
"Sprite width to use (How you want it to look?)"
"Sprite height to use"
)
*/
//(sprite.png,0,0,300,300,0,0,300,300)
ctx.drawImage(myImage, shift, 0, frameWidth, frameHeight, canvasX, canvasY, frameWidth, frameHeight);
shift += frameWidth + 1;
}
if (currentFrame == totalFrames) {
shift = 0;
currentFrame = 0;
}
currentFrame++;
requestAnimationFrame(animate);
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- What code do we need? -->
<script src ="exercise_three.js"></script>
</head>
<body>
<canvas width="300" height="300" style="border: solid black 1px">
Sorry, no canvas support!
</canvas>
</body>
</html>
https://jsfiddle.net/r7dd2mt7/2/RequestAnimationFrame()
我将非常感谢一些帮助理解它的工作原理。
【问题讨论】:
标签: javascript