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
相关产品推荐
相关产品推荐

