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

为何设置ctx.lineCap="round"时,ctx.roundRect左上角出现微小圆点?

Chromium内核Canvas绘制圆角矩形时的左上角圆点问题分析

这确实是Chromium内核浏览器的已知渲染bug,Firefox的Canvas路径处理逻辑不存在这个问题。

问题原因

当你将ctx.lineCap设置为"round",调用roundRect创建圆角矩形路径后执行closePath()时,Chromium渲染引擎在处理闭合路径的起点与终点时,错误地额外渲染了一个圆形端点。实际上roundRect生成的路径本身已经是闭合状态,额外调用closePath()会导致路径起点和终点在圆角位置重复叠加,触发了这个bug。

复现代码

const ctx = canvas.getContext('2d')

let width = window.innerWidth
let height = window.innerHeight

canvas.width = width
canvas.height = height

ctx.clearRect(0,0,canvas.width, canvas.height)
ctx.lineWidth = 5
ctx.strokeStyle = "black"
ctx.lineCap = "round"
ctx.beginPath()
ctx.roundRect(100,100,100,100,12)
ctx.closePath()
ctx.stroke()

解决方案

可以通过以下几种方式规避该问题:

  • 移除closePath()调用:roundRect生成的路径默认是闭合的,无需额外执行闭合操作
  • 调整lineCap设置时机:如果业务允许,可在绘制完成后再将lineCap设置为"round"
  • 临时切换lineCap:若必须保留closePath(),可在stroke()前将lineCap临时改为默认的"butt",绘制完成后再改回"round"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 06:29:54