如何在javascript中更改画布中动画的颜色?

问题描述 投票:0回答:1

我有一个动画递归函数,可以将正方形从画布顶部移动到底部。然后,我想使用 ctx.fillStyle 将其颜色更改为红色。我看不到错误。或者也许,我不明白一些事情。

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

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

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

function changeColor(){ ctx.fillStyle = 'red'; }
javascript animation canvas
1个回答
1
投票

您每秒将颜色更改为红色一次。但每次调用函数 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>

© www.soinside.com 2019 - 2024. All rights reserved.