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

HTML5 Canvas横竖线显示为2像素宽的问题求助

在HTML5 Canvas绘制1像素宽线条的问题
  • 在HTML5 Canvas上绘制水平和垂直线条时,始终无法得到1像素宽的清晰渲染效果。
  • 已尝试的解决方案包括:将坐标偏移0.5、平移画布0.5、按devicePixelRatio缩放画布宽高、直接获取画布图像操作像素数据。
  • 显示差异:在高DPI屏幕(如Surface Pro)上,偏移0.5像素结合devicePixelRatio缩放画布的方法有效,能得到清晰的1像素宽线条;但在1920×1080标准显示器(devicePixelRatio == 1)上,线条仍显示为2像素宽。
  • 已知问题根源可能是像素边界绘制导致,理论上0.5偏移应能解决,但实际测试中该方案无效。

测试代码

const canvas = document.getElementById("canvas");

const dpi = window.devicePixelRatio;

const rect = canvas.getBoundingClientRect();

canvas.width = rect.width * dpi;
canvas.height = rect.height * dpi;

canvas.style.width = `${rect.width}px`;
canvas.style.height = `${rect.height}px`;

const rowHeight = 25;
const colWidth = 100;

const ctx = canvas.getContext("2d");

ctx.scale(dpi,dpi);

ctx.beginPath();

ctx.strokeStyle = '#bdbdbd';

for(let i = rowHeight + 0.5; i < canvas.height; i += rowHeight){
  
  ctx.moveTo(0,i);
  ctx.lineTo(canvas.width,i);
  
}

for(let i = colWidth + 0.5; i < canvas.width; i += colWidth){
  
  ctx.moveTo(i,0);
  ctx.lineTo(i,canvas.height);
  
}

ctx.stroke();
  • 曾尝试将SVG作为图像应用到画布,结果不符合预期。
  • 研究过Glide-Data-Grid项目,其演示在我的显示器上能正常渲染1像素宽线条,但对比该项目标准的网格绘制逻辑,仍未找到自身代码的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:15:45