【发布时间】:2014-04-15 10:15:55
【问题描述】:
我需要在我的 html5 画布上有一个动态图像,这将是一个动画,而无需单击按钮来启动它。 谁能帮帮我?
谢谢
【问题讨论】:
-
您希望它如何制作动画? (乒乓球,弹跳,随机,...)。请与我们分享您目前拥有的代码。如果可能的话,还请包括一个小提琴。
标签: html animation canvas web html5-canvas
我需要在我的 html5 画布上有一个动态图像,这将是一个动画,而无需单击按钮来启动它。 谁能帮帮我?
谢谢
【问题讨论】:
标签: html animation canvas web html5-canvas
这里是一些注释代码和一个演示: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>
【讨论】: