javascript - 如何使用 javascript 更改 Canvas 中动画的颜色?

标签 javascript animation canvas

我有一个动画递归函数,可以将正方形从 Canvas 的顶部移动到底部。然后,我想通过使用 ctx.fillStyle 将他的颜色更改为红色。它应该可以工作,但程序流程中可能存在错误。我看不到错误。或许,我不明白什么。

我使用了全局变量并尝试在不同的地方调用该函数。

https://jsbin.com/cavuwak/edit?html,css,js,output

function init() {
    setInterval(changeColor, 1000); }

function changeColor(){ ctx.fillStyle = 'red'; }

最佳答案

您每秒将颜色更改为红色一次。但是每次调用函数 animate() 时,它都会将颜色变回蓝色。 requestAnimationFrame(animate) 大约每 6ms-12ms 触发一次,具体取决于您的硬件。 这里建议使用您的代码进行修复:

var canvas, ctx, squareY = 10;
var currentColor = 0;
var colors = ['blue', 'red', 'green'];
 //First change: add variable to hold current color
var color = 0;

window.onload= init;

function init() {
  canvas = document.querySelector('#myCanvas');
  ctx = canvas.getContext('2d');
  
  drawTwoRect();
  
  requestAnimationFrame(animate);
  var a = setInterval(changeColor, 1000);
  
}

function drawTwoRect() {
    ctx.fillStyle = 'green';
    ctx.fillRect(10,10,100,100);
    ctx.fillStyle = 'red';
    ctx.fillRect(120,10,60,60);
  
  
}

function animate() {
  ctx.clearRect(0,0, canvas.width,canvas.height);
//Second change: use your array colors to change the color.
  ctx.fillStyle = colors[color];
  ctx.fillRect(190,squareY,30,30);
  
  squareY++;
  
  if(squareY === 100) squareY = 0;
  requestAnimationFrame(animate);
  
}

function changeColor() {
//Third change: flip the value in global color. Like this, the square changes its color every second.
  color = Math.abs(color-1);
  // if you want to change the color only once, just set color = 1:
  // color = 1;
}
#myCanvas {
  border: 2px dotted
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <canvas id="myCanvas" width=300px heigth=300px >
  We usually write a small message</canvas>
</body>
</html>

关于javascript - 如何使用 javascript 更改 Canvas 中动画的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56299797/

相关文章:

javascript - 如何在 Javascript 函数中隐藏或散列值?

javascript - $modal 没有按预期工作

c# - 在 WPF 中使用另一个页面上的现有 Canvas

javascript - 如何创建一个可以访问函数及其对象的 JavaScript 包装器?

javascript - Firebase 顺序按降序排列

javascript - Three.js简单的粒子动画

android - Android 中的高级 View 动画

matplotlib - 无法从 'animation' 导入名称 'matplotlib'

javascript - clearTimeout 不停止 Canvas 动画

javascript - 垂直视差无法使用 Parallax.js