接上篇, 地址
需求更新:
繪制的海報(bào)要求有圓角汞窗,其他設(shè)置一如既往
技術(shù)思路
- 畫(huà)圓角矩形先鱼,然后裁剪此為畫(huà)布區(qū)域
- 在上一畫(huà)布區(qū)域進(jìn)行繪制圖片浆竭,即可
- 其他照常
涉及API
Canvas.MoveTo, .lineTo, .arc, .drawImage, .clip
// 畫(huà)布归敬,圖片獲取等
const canvas = document.getElementById('canvas')
const context = canvas.getContext('2d')
const img = document.getElementById('img')
img.onload = ()=>{
// 繪制圓角矩形
drawRoundedRect(context, 0, 0, canvas.width, canvas.height, 14);
// 畫(huà)布裁切
context.clip()
// 海報(bào)繪制到裁切后的畫(huà)布上
context.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0,canvas.width, canvas.height);
// 導(dǎo)出畫(huà)布為圖片
document.getElementById("canvas_img").src = canvas.toDataURL('image/png')
}
// 繪制圓角矩形
function drawRoundedRect (ctx, x, y, width, height, radius) {
ctx.moveTo(x + radius, y)
ctx.lineTo(x + width - radius, y)
ctx.arc(x + width - radius, y + radius, radius, 1.5 * Math.PI, 2 * Math.PI)
ctx.lineTo(x + width, y + height - radius)
ctx.arc(x + width - radius, y + height - radius, radius, 0, 0.5 * Math.PI)
ctx.lineTo(x + radius, y + height)
ctx.arc(x + radius, y + height - radius, radius, 0.5 * Math.PI, 1 * Math.PI)
ctx.lineTo(x, y + radius)
ctx.arc(x + radius, y + radius, radius, 1 * Math.PI, 1.5 * Math.PI)
}
效果圖如下
image
Tips:
- canvas.toDataURL時(shí)候類(lèi)型請(qǐng)選擇為 image/png烁设,而非其他類(lèi)型,否則會(huì)出現(xiàn)四個(gè)黑色角
- 解決清晰度問(wèn)題撬腾,請(qǐng)參考上一篇文章
本示例完整代碼地址: 傳送門(mén)