我是HTML5 Canvas的新手。我一直在努力建造形状,但是,我无法得到一个明星,我创造了一个'#34;射击明星时尚"。如果你能帮助我让明星移动,至少在整个屏幕上移动,这将是非常有用的。
以下是代码:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
function drawStar(cx, cy, spikes, outerRadius, innerRadius) {
var rot = Math.PI / 2 * 3;
var x = cx;
var y = cy;
var step = Math.PI / spikes;
ctx.strokeSyle = "#000";
ctx.beginPath();
ctx.moveTo(cx, cy - outerRadius)
for (i = 0; i < spikes; i++) {
x = cx + Math.cos(rot) * outerRadius;
y = cy + Math.sin(rot) * outerRadius;
ctx.lineTo(x, y)
rot += step
x = cx + Math.cos(rot) * innerRadius;
y = cy + Math.sin(rot) * innerRadius;
ctx.lineTo(x, y)
rot += step
}
ctx.lineTo(cx, cy - outerRadius)
ctx.closePath();
ctx.lineWidth=1;
ctx.strokeStyle='#0797c4';
ctx.stroke();
ctx.fillStyle='#0797c4';
ctx.fill();
}
drawStar(75, 100, 5, 30, 15);
答案 0 :(得分:0)
使用requestAnimationFrame
(rAF)作为动画循环来移动你的星星。
典型的rAF循环如下:
// start the animation
requestAnimationFrame(animate);
function animate(time){
// change the x,y position of your star
// clear the canvas and draw your star at the new x,y
// request another frame
}
这是带注释的代码和演示:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
// for efficiency, create the star once on an in-memory canvas
var star=makeStarCanvas(31, 31, 5, 30, 15);
// the star's current x position
var x=0;
ctx.drawImage(star,x,110);
$('#go').click(function(){
// start the star at x=0
x=0;
// use requestAnimationFrame to animate the star
requestAnimationFrame(animate);
});
function animate(time){
// move the star rightward
x+=1;
// move the star vertically in a sine wave pattern
var y=Math.sin(x/(cw/4))*-100+110;
// draw the star canvas onto the main canvas
ctx.clearRect(0,0,cw,ch);
ctx.drawImage(star,x,y);
// continue animating if the star hasn't moved off the canvas
if(x<cw){ requestAnimationFrame(animate); }
}
// make an in-memory canvas with a star drawing
function makeStarCanvas(cx, cy, spikes, outerRadius, innerRadius) {
var c=document.createElement('canvas');
var cctx=c.getContext('2d');
var rot = Math.PI / 2 * 3;
var x = cx;
var y = cy;
var step = Math.PI / spikes;
cctx.strokeSyle = "#000";
cctx.beginPath();
cctx.moveTo(cx, cy - outerRadius)
for (i = 0; i < spikes; i++) {
x = cx + Math.cos(rot) * outerRadius;
y = cy + Math.sin(rot) * outerRadius;
cctx.lineTo(x, y)
rot += step
x = cx + Math.cos(rot) * innerRadius;
y = cy + Math.sin(rot) * innerRadius;
cctx.lineTo(x, y)
rot += step
}
cctx.lineTo(cx, cy - outerRadius)
cctx.closePath();
cctx.lineWidth=1;
cctx.strokeStyle='#0797c4';
cctx.stroke();
cctx.fillStyle='#0797c4';
cctx.fill();
return(c);
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id='go'>Animate</button>
<br>
<canvas id="canvas" width=300 height=300></canvas>