高级前端js【Q230】如何裁剪图片 (情景:选择头像)

如何裁剪图片 (情景:选择头像)

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 231

Author 回答者: HuiFeiYa

var path = 'https://static-zh.wxb.com.cn/customer/form/2020/11/1758696796d.jpg'
function clipImage(path){
    const canvas = document.createElement('canvas')
    canvas.width = 200
    canvas.height = 100
    const ctx = canvas.getContext('2d')
    const img = document.createElement('img')
    img.src = path
    img.setAttribute("crossOrigin",'Anonymous')
    img.onload = function (){
        ctx.drawImage(this,0,0,200,100)
        console.log(canvas.toDataURL())
    }
}
clipImage(path)

Author 回答者: jkLennon

使用ctx.arc()和ctx.clip()进行裁剪 ctx.arc(x, y, radius, startAngle, endAngle); ctx.clip(); ctx.drawImage(img, x, y, width, height)