You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Safari中HTML5 Canvas Context更新异常问题求助

Safari专属HTML5 2D Canvas描边颜色异常问题

更新:此问题已提交为WebKit Bug报告
更新:我添加了由@Kaiido协助编写的代码片段,相关示例中该Bug表现更明显。

我遇到了一个仅在Safari中出现的HTML5 2D Canvas异常,Chrome和Firefox中完全正常,这个问题影响了已经上线5年的网站。

我的Canvas绘制代码如下,部分线条会出现颜色未正确应用的闪烁现象:

const canvasWidth = 600;
const gapBetweenLines = 5;
const nbrLines = canvasWidth / gapBetweenLines;
const canvasHeight = 100;

const canvas = document.getElementById('map');
canvas.width = canvasWidth;
canvas.height = canvasHeight;

// 创建线条对象数组,每条线带随机颜色
let lines = [];
for (let i = 0; i < nbrLines; i++) {
  lines.push({
    index: i,
    x: i * gapBetweenLines,
    color: '#' + Math.floor(Math.random() * 16777215).toString(16)
    // 强制6位长度
      .padStart(6, "0")
  });
}

// 原地打乱数组的函数
function shuffle(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
}

// 按指定间隔在画布上绘制带随机颜色的线条
function drawLines() {
  const shuffledLines = [...lines];
  shuffle(shuffledLines);

  let ctx = canvas.getContext('2d');
  for (let i = 0; i < nbrLines; i++) {
    const line = shuffledLines[i];
    ctx.strokeStyle = line.color;
    ctx.beginPath();
    ctx.moveTo(line.x, 0);
    ctx.lineTo(line.x, canvasHeight);
    ctx.stroke();
  }
}

// 每200ms调用一次drawLines函数
setInterval(drawLines, 200);
<!DOCTYPE html>
<html>
  <body>
    <h1>Flickering Lines</h1>
    <canvas id="map"></canvas>
    <div id="lineinfo"></div>
  </body>
</html>

在Safari中,线条的描边颜色无法始终正确设置为指定的strokeStyle值,仿佛部分strokeStyle赋值被忽略。所有线条都能绘制,但很多线条保留了上一轮循环的颜色。

这似乎是stroke()的基础使用场景,我找不到问题所在,恳请各位提供建议。

内容的提问来源于stack exchange,提问作者jowo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 15:40:41