參考:
https://www.jb51.net/article/146092.htm
https://blog.csdn.net/CrazBarry/article/details/96149496
如下沒有所謂鋸齒問題,參考鏈接中說的鋸齒可能是弧線跟直線交叉,或者邊線重疊產生的。
/** * * @param {CanvasContext} ctx canvas上下文 * @param {number} x 圓角矩形選區的左上角 x坐標 * @param {number} y 圓角矩形選區的左上角 y坐標 * @param {number} w 圓角矩形選區的寬度 * @param {number} h 圓角矩形選區的高度 * @param {number} r 圓角的半徑 */ roundRect(ctx, x, y, w, h, r) { // 開始繪制 ctx.setLineDash(); ctx.save(); // 保存當前已繪制,不然后面繪制的都顯示不了 ctx.beginPath(); ctx.setFillStyle('#fff'); ctx.setStrokeStyle('#BEBEBE'); // 左上角 ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5); // 右上角 ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2); // 右下角 ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5); // 左下角 ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI); // border-left ctx.lineTo(x, y + r); ctx.fill(); ctx.stroke(); ctx.closePath(); // 剪切 ctx.clip(); ctx.restore(); // 恢復clicp的繪制區域,后面的都能繪制 ctx.draw(true); }
效果截圖: