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

Canvas生成色盲图问题:下载尺寸不符及点图案显示不全

问题修复方案

问题1:下载图片尺寸不符、圆点未铺满

原代码中html2canvas的width/height参数并非强制生成对应尺寸画布,且绘制圆点的循环未覆盖画布边缘,同时下载后重置容器尺寸会导致异常。修复点:

  • 移除html2canvas的width/height配置,依赖容器本身的600*600尺寸
  • 绘制圆点时循环条件改为x <= canvas.width和y <= canvas.height,确保铺满整个画布
  • 删除下载后重置容器尺寸的代码,避免破坏原有布局

问题2:Stackoverflow中下载按钮失效

这是Stackoverflow的沙箱安全策略限制导致的,代码本身在常规环境可正常运行。可通过调整下载触发时机优化兼容性:

  • 将链接点击操作放入requestAnimationFrame中,绕过沙箱的即时点击限制

修复后的完整代码

HTML

<html>
<head>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
</head>
<body>
<div id="container">
    <div id="text">LOVE</div>
    <div class="dotted"></div>
</div>

<button onclick="generateColorBlindImage()">Generate Color Blind Image</button>
<button onclick="downloadImage()">Download Image</button>
</body>
</html>

CSS

#container {
  position: relative;
  width: 600px;
  height: 600px;
  background-color: lightgray;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

#text {
  font-size: 48px;
  font-family: Arial, sans-serif;
  color: red;
  opacity: 0.5;
}

.dotted {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: none;
}

JavaScript

var dotRatio = 20;

function generateColorBlindImage() {
  document.getElementById('text').style.opacity = 0.2;
  document.querySelector('.dotted').style.display = 'block';
}

function downloadImage() {
  const containerElement = document.getElementById('container');
  document.querySelector('.dotted').style.display = 'block';

  html2canvas(containerElement, { useCORS: true }).then(function(canvas) {
    const ctx = canvas.getContext('2d');
    const patternSize = dotRatio;
    // 修正循环条件,确保圆点铺满整个画布
    for (let x = 0; x <= canvas.width; x += patternSize) {
      for (let y = 0; y <= canvas.height; y += patternSize) {
        ctx.fillStyle = 'black';
        ctx.beginPath();
        ctx.arc(x, y, 2, 0, 2 * Math.PI);
        ctx.closePath();
        ctx.fill();
      }
    }

    const link = document.createElement('a');
    link.href = canvas.toDataURL('image/png');
    link.download = 'color_blind_image.png';
    
    // 调整触发时机,适配沙箱环境
    requestAnimationFrame(() => {
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });

    document.querySelector('.dotted').style.display = 'none';
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 06:15:38