4

我是 html5 开发的新手,谁能告诉我如何使文本在画布内水平移动到另一侧..

4

2 回答 2

6

这是一个如何在屏幕上来回动画文本的示例:

<html>
   <head>
   <title>HTML 5 Animated Text</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript">
        var context;
        var text = "";
        var textDirection ="";

        $(function()
        {
            context = document.getElementById("cvs").getContext("2d");            
            setInterval("animate()", 30);

            textDirection ="right";
            textXpos = 5;
            text = "Animation!";    
        });  

        function animate() {            
            // Clear screen
            context.clearRect(0, 0, 500, 500);
            context.globalAlpha = 1;
            context.fillStyle = '#fff';
            context.fillRect(0, 0, 500, 500);    

            var metrics = context.measureText(text);
            var textWidth = metrics.width;

            if (textDirection == "right") {
                textXpos += 10;

                if (textXpos > 500 - textWidth) {
                    textDirection = "left";
                }
            }
            else {
                textXpos -= 10;

                if (textXpos < 10) {
                    textDirection = "right";
                }                    
            }

            context.font = '20px _sans';
            context.fillStyle = '#FF0000';
            context.textBaseline = 'top';
            context.fillText  ( text, textXpos, 180);    
          }    
          </script>
      </head>
      <body> 
         <div id="page">
            <canvas id="cvs" width="500" height="500">
               Your browser does not support the HTML 5 Canvas. 
            </canvas>
         </div>
      </body>
   </html>

在行动:http: //jsfiddle.net/bS79G/

于 2012-07-12T11:04:59.177 回答
1

您还可以使用画布的 store()、translate() 和 restore() 方法为文本设置动画。假设如果要将文本从右侧移动到左侧,则可以使用以下代码段:

参考网站:http ://www.authorcode.com/text-animation-in-html5/

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);
    }
于 2013-04-19T08:57:14.553 回答