要删除HTML5 Canvas中的文本?

凯索

我正在处理HTML5 Canvas项目,并且在屏幕上绘制了一些文本。现在,它出现并停留在那里,但是我需要的是让它在几秒钟后消失,以便每次调用它时,不仅仅是在旧文本之上绘制新文本。

我尝试了clearRect(),但是它完全清除了整个矩形并也删除了一些我不想要的背景。

有没有办法做到这一点?

我使用以下基本功能绘制文本:

    function drawText() {

        ctx.font = "30px Arial";
        ctx.fillText("Please wait...", 575, 130);

    }
德文·菲尔德

<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <button onclick="showTheText()">Click to show text</button>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');
      
      function showTheText() {
        var myText = {
          text: 'Hello World',
          x: 0,
          y: 75,
          fill: 1
        };

        drawText(myText, context);

        // wait one second before starting animation
        setTimeout(function() {
          animate(myText, canvas, context);
        }, 1000);
      }

      function drawText(myText, context) {
        context.font="30px Arial";
        context.fillStyle="rgb(0, 0, 0, " + myText.fill + ")";
        context.fillText(myText.text, myText.x, myText.y);
      }
      function animate(myText, canvas, context) {
        // clear
        context.clearRect(0, 0, canvas.width, canvas.height);
        // !!!!!!!! redraw your background !!!!!!!!

		    // then redraw your text with new opacity
        myText.fill -= .1;
        drawText(myText, context);

        // request new frame
        if (myText.fill > -.1) {
          setTimeout(function() {
            animate(myText, canvas, context);
          }, 2000 / 60);
        }
      }

    </script>
  </body>
</html>  

希望这可以帮到你。它的作用是立即绘制文本(其余的背景,您没有提供),然后设置递归超时,以清除矩形,重新绘制背景,减少应用于文本的不透明度填充并重新绘制文本。您可以通过更改上一个setTimeout的时间来减慢它的速度。

我根据以下示例进行了改编:https : //www.html5canvastutorials.com/advanced/html5-canvas-animation-stage/

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章