【问题标题】:Canvas strokeStyle not changing in internet explorer画布strokeStyle在Internet Explorer中没有改变
【发布时间】:2022-01-06 00:15:37
【问题描述】:

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

我希望线条的颜色在绘制时淡入下一个颜色。这在 Chrome 中运行良好,但在 Internet Explorer 中,strokeStyle 不会在每一步都更新。

我已经包含了一个指向显示问题的 sn-p 的链接:

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>

【问题讨论】:

  • 编辑您的帖子,而不是 jsbin,并使用 runnable snippet 选项。 Stackoverflow 内置了“jsbin”。但请注意,自 IE9 以来,IE 已经拥有相当可靠的 Canvas2D 支持,因此您几乎可以肯定首先必须运行 minimal reproducible example 练习,将您的代码缩减到完全 足以炫耀不起作用的东西。而且它可能不是 strokeStyle 属性本身(很有可能在运行 MCVE 练习时,您自己发现了真正的问题)。
  • 尝试.toFixed(2) colorTween 函数中的值,IIRC IE 确实会阻塞 rgba(r,g,b,0.verylongdecimalnumberhere)
  • @Kaiido 谢谢,这正是问题所在!

标签: javascript internet-explorer canvas html5-canvas


【解决方案1】:

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);

【讨论】:

  • 谢谢,我的 rgb 值也有小数;由于我的补间函数的划分。在 rgb 值上有任何小数位也会导致 strokeStyle(我也假设为 fillStyle?)不会在 Internet Explorer 上更新。
  • 并且 R、G、B 上的小数位数有限还是可以的,或者这需要是 int 吗?我不记得了,现在也无法访问 IE。
  • 只有当 R,G,B 值是整数时才有效。另外,经过测试,我发现我不需要 .toFixed(3) 来使 alpha 值在 ie11 中起作用;只需要确保 RGB 值是整数! ctx.strokeStyle = "rgba("+Math.round(drawColor[0])+","+Math.round(drawColor[1])+","+Math.round(drawColor[2])+","+drawColor[3].toFixed(3)+")";
  • 好的,我稍后会修改我的答案,感谢您的反馈
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-04
  • 1970-01-01
  • 2015-09-28
  • 2015-04-10
  • 1970-01-01
  • 2012-11-16
相关资源
最近更新 更多