为什么我的多个 canvas 动画(requestAnimationFrame)只对一个元素有效?

Why my multiple canvas animation(requestAnimationFrame) is working only for one element?

我不明白为什么我的代码中的 requestAnimationFrame 只对一个元素起作用。我想为两个边框设置动画...我在 codepen 中的代码 -> http://codepen.io/zey_ser/pen/RPXovp

<div>
  <div id="valueForAnimation" style="display:none;">10</div>
  <canvas id="myCanvas" width="100" 
   height="100"></canvas>
</div>
<div>
  <div id="valueForAnimation2" style="display:none;">85</div>
  <canvas id="myCanvas2" width="100" 
   height="100"></canvas>
</div>
<button onclick="stop()">Stop animation</button>

animatedBorders('#myCanvas','valueForAnimation');
animatedBorders('#myCanvas2','valueForAnimation2');
///////////////////////////////////////////////////////////////////////////////////////////////
function animatedBorders (selector,selectorValue){  
canvas = document.querySelector(selector);
ctx = canvas.getContext('2d');
...
////////////////////
drawRect();
ID = requestAnimationFrame(animationLoop);
drawText();
////////////////////
function drawRect(){
...
}
function drawLine(){
...
}
function drawText(){
...
}

function animationLoop(){
  drawLine();
}
}

你忘了使用 var ctx 省略了这个你创建了一个变量 window.ctx,你的函数第二次运行时第一个 ctx 被第二个覆盖了,这就是为什么只有第二个运行。

animatedBorders 函数的前 3 行应该如下所示:

function animatedBorders(selector, selectorValue) {
  canvas = document.querySelector(selector);
  var ctx = canvas.getContext('2d');

唯一值得注意的变化是在 ctx

之前添加了 var