在html页面中随机出现文本

时间:2015-06-10 17:35:54

标签: javascript html5 css3 canvas html5-canvas

我一直在努力研究解决方案,但是空洞。

我正在尝试在我的文档中的画布上从不同的方向制作10个不同字体大小的单词。我有一些代码(jsFiddle),但没有设法得到太多,所有建议都表示赞赏。

var can, ctx, step, steps = 0,
  delay = 20;

function init() {
  can = document.getElementById("MyCanvas1");
  ctx = can.getContext("2d");
  ctx.fillStyle = "blue";
  ctx.font = "20pt Verdana";
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  step = 0;
  steps = can.height + 50;
  RunTextRightToLeft();
}

function RunTextRightToLeft() {
  step++;
  ctx.clearRect(0, 0, can.width, can.height);
  ctx.save();
  ctx.translate(can.width / 2, step);
  ctx.fillText("Welcome", 0, 0);
  ctx.restore();
  if (step == steps)
    step = 0;
  if (step < steps)
    var t = setTimeout('RunTextRightToLeft()', delay);
}
canvas {
  border: 1px solid #bbb;
}
.subdiv {
  width: 320px;
}
.text {
  margin: auto;
  width: 290px;
}
<body onload="init();">
  <div class="subdiv">
    <canvas id="MyCanvas1" width="300" height="200">
    </canvas>
  </div>
</body>

谢谢

1 个答案:

答案 0 :(得分:0)

这是将单词动画化为最终句子的一种方法:

https://jsfiddle.net/m1erickson/q7tpsnmv/

在数组中定义一些单词对象:

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<words.length;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<words.length;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<words.length){
        requestAnimationFrame(animate);
    }
}