我需要在我的html5画布上有一个动态图像,这将是一个动画,而无需单击按钮来启动它。 有谁可以帮助我?
谢谢
答案 0 :(得分:1)
以下是一些注释代码和演示:http://jsfiddle.net/m1erickson/8wY6K/
它的工作原理如下:
代码:
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: white; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
// canvas related variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
// define a circular path
// for our image to travel
var cx=50;
var cy=50;
var radius=40;
// a variable to hold the current degree of rotation
var degreeAngle=0;
// load an image
// when the image is fully loaded, call start()
// start() will start the animation loop
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/ship.jpg";
function start(){
animate();
}
// this is an animation loop
// using requestAnimationFrame
function animate(){
// request that this animate() function be called again
// this creates an animation loop
requestAnimationFrame(animate);
// clear the canvas
// calculate the new position of the image
// this example just rotates it around a centerpoint
degreeAngle+=1;
var radianAngle=degreeAngle*Math.PI/180;
var x=cx+radius*Math.cos(radianAngle);
var y=cy+radius*Math.sin(radianAngle);
// clear the canvas
// and draw the image at its new position
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(img,x,y);
}
}); // end $(function(){});
</script>
</head>
<body>
<button id="test">Test</button><br>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>