canvas 圖片圓角問題
阿新 • • 發佈:2020-07-13
引子
近期的工作中,是繼 canvas 設定邊框問題 之後碰到的第 4 個問題。
圖片圓角問題
如果只是想要顯示圓角的效果,設定 border-radius
就可以了,但如果要讓 canvas 合成的圖片顯示為圓角,這種 css 方式不行。這是示例,掃描訪問二維碼如下。
在網上查詢資料,發現同樣的問題,解決的方式是用 canvas 的裁剪功能。
解決方法
先畫布上畫一個有圓角的矩形,然後使用裁剪的方式 clip()
。
// 生成有圓角的矩形 function drawRoundedRect(cxt, x, y, width, height, radius) { cxt.beginPath(); cxt.arc(x + radius, y + radius, radius, Math.PI, Math.PI * 3 / 2); cxt.lineTo(width - radius + x, y); cxt.arc(width - radius + x, radius + y, radius, Math.PI * 3 / 2, Math.PI * 2); cxt.lineTo(width + x, height + y - radius); cxt.arc(width - radius + x, height - radius + y, radius, 0, Math.PI * 1 / 2); cxt.lineTo(radius + x, height + y); cxt.arc(radius + x, height - radius + y, radius, Math.PI * 1 / 2, Math.PI); cxt.closePath(); }
這是示例,掃描訪問二維碼如下。