【问题标题】:Canvas issues with updating画布更新问题
【发布时间】:2014-07-20 11:31:10
【问题描述】:
<canvas id="ctx" width="500" height="500" style="border:1px solid #000000;"> 

<script type="text/javascript">
 window.onload = function() {
var ctx = document.getElementById("ctx").getContext("2d"); 
    function createText(words) {
     var LENGTH = words.length;
     var LOOPS = LENGTH;
     var reader = 0;

     position = 10;
     while( LOOPS > 0) {
     letter = words.substr(reader,1);

     setTimeout(ctx.fillText(letter,position,10),100); 
     position += 6; 
     reader += 1; 
     LOOPS -= 1; 
      }

    }


    createText("Hello, how are you?");      

    }
</script>


</canvas> 

我希望它像打字动画那样在打印每个字母之前暂停几分之一秒,而是同时加载所有字母。我做错了什么?

【问题讨论】:

    标签: javascript html canvas text updating


    【解决方案1】:

    所以有几件事让这对你不起作用,因为setTimeout 你的ctx.fillText 被立即调用,一旦循环命中它。要停止这种情况,您需要将其包装在 function 中,以便在超时期间调用它。

    setTimeout(function(){
        // your logic here.
    }, 100);
    

    但是,如果您这样做,您将遇到一个常见问题,即您只会收到 last 字母 due to the way variable scoping works in JavaScript。要解决此问题,您需要将函数包装在闭包中并将值传递给它。

    // loop start
     a++;
     b++;
     setTimeout(
        (function (a,b) {
             return function () {
                 // some logic that uses a and b
             }
     })(a, b), 100);
    // loop end
    

    最后发生的事情是您的超时设置为 100.. 所以它仍然会立即发生。这意味着每次超时都会在 100 毫秒后触发,因为创建循环非常快。为了解决这个问题,您需要在某处保存延迟并在循环中增加延迟,以便它们一个接一个地发生。例如第一个会延迟 100ms,下一个会延迟 200ms,然后是 300,等等。

    // loop start
     a++;
     b++;
     // Increase the time delay each loop iteration
     timeDelay += 100;
    
     setTimeout(
        (function (a,b) {
             return function () {
                 // some logic that uses a and b
             }
     })(a, b), timeDelay);
    // loop end
    

    完整的工作代码和演示

    Live Demo

     window.onload = function () {
         var ctx = document.getElementById("ctx").getContext("2d");
    
         function createText(words) {
             var LENGTH = words.length;
             var LOOPS = LENGTH;
             var reader = 0;
             var timeDelay = 100;
    
             position = 10;
    
             while (LOOPS > 0) {
                 letter = words.substr(reader, 1);
    
                 setTimeout((function (letter, position) {
                     return function () {
                         ctx.fillText(letter, position, 10);
                     }
                 })(letter, position), timeDelay);
    
                 position += 6;
                 reader += 1;
                 LOOPS -= 1;
                 timeDelay += 100;
             }
    
         }
    
         createText("Hello, how are you?");
    
     }
    

    【讨论】:

    • 哇,谢谢!这是我得到的最有用的回复之一。我不完全理解超时功能是如何工作的,但现在我明白了,那太好了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2014-01-08
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    • 2011-09-08
    • 2013-07-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多