这是将单词动画化为最终句子的一种方法:
在数组中定义一些单词对象:
var words=[];
words.push({
text:'Welcome',
// starting x,y of the word offscreen
x0:Math.random()*cw,
y0:(Math.random()*100)+ch,
// ending position of the word onscreen
x1:20,
y1:50,
// font-size
size:10,
// delay before starting to animate this word in
delay:200,
// the animations progress (percent-complete)
pct:0
});
计算每个单词必须最终成为句子的位置:
var accumX=0;
for(var i=0;i
w=words[i];
// measure this word and assign it's ending x1 appropriately
ctx.font=w.size+'px verdana';
var width=ctx.measureText(w.text).width;
w.x1=accumX;
accumX+=(width+8);
// dx,dy are used to calculate the interim waypoints
// for the word as it animates in
w.dx=w.x1-w.x0;
w.dy=w.y1-w.y0;
}
将每个单词从其起始位置[x0,y0]动画到其结束位置[x1,y1]:
var start=performance.now();
requestAnimationFrame(animate);
function animate(time){
var countComplete=0;
// clear the canvas for this new frame
ctx.clearRect(0,0,cw,ch);
for(var i=0;i
var w=words[i];
if(w.pct==100){countComplete++;}
// calc the appropriate x,y waypoint
var x=w.x0+w.dx*w.pct/100;
var y=w.y0+w.dy*w.pct/100;
w.pct=Math.min(100,w.pct+1);
// draw the text
ctx.font=w.size+'px verdana';
ctx.fillText(w.text,x,y);
}
// request another loop if the animation is not complete
if(countComplete
requestAnimationFrame(animate);
}
}