Canvas strokeStyle 在 Internet Explorer 中没有改变

Canvas strokeStyle not changing in internet explorer

我正在尝试让网页屏幕保护程序在 windows 10 上运行,但它使用的是 Internet Explorer :(

我希望线条的颜色在绘制时淡入下一种颜色。这在 Chrome 中工作正常,但在 Internet Explorer 中,strokeStyle 不会在每一步都更新。

我已将 link 添加到显示问题的片段中:

function colorTween(from, to, step, maxStep) {
    const newColor = [0,0,0,0];
    from.forEach(function (fromVal, i) {
        const toVal = to[i];
        newColor[i] = fromVal + (((toVal - fromVal)/maxStep)*step);
    });
    return newColor;
}

//init
const canvas = document.getElementById('canvas'); 
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.lineWidth = 50;
ctx.lineCap = "round";

const fromColor = [0,0,0,1]; //black
const toColor = [255,255,255,1]; //white

const y = canvas.height/2;
let x = 0;
let prevX = 0;

//draw loop
setInterval(function () {
    //increase x
    x++;

    //get color fading into next color
    const drawColor = colorTween(fromColor, toColor, x, canvas.width);
      
    //draw line segment
    ctx.strokeStyle = "rgba("+drawColor[0]+","+drawColor[1]+","+drawColor[2]+","+drawColor[3]+")";

    ctx.beginPath();
    ctx.moveTo(prevX, y);
    ctx.lineTo(x, y);
    ctx.stroke();
    ctx.closePath();

    //setup for next loop
    prevX = x;
}, 1000/60);
body, canvas {
    margin: 0;
    padding: 0;
    border: none;
    overflow: none;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <canvas id="canvas"></canvas>
</body>
</html>

Internet Explorer 确实因 RGB CSS 值中的十进制数字过多而窒息(strokeStyle 被解析为 CSS 值)。
您的 colorTween 函数很可能会产生这样的十进制数字,而 IE 将完全忽略该值。

为避免这种情况,请四舍五入您的 R、G 和 B 值,虽然我不确定是否需要它,但您可能还想对 Alpha 值调用 .toFixed()(对于 R、G、 B 小数点无论如何都会被实现丢弃,对于 alpha,最大粒度是 1/256,即 ~0.004)。

from.forEach(function (fromVal, i) {
  const toVal = to[i];
  const newVal = fromVal + (((toVal - fromVal)/maxStep)*step);
  newColor[i] = i===3 ? newVal.toFixed(3) : Math.round(newVal);