Canvas 绘制图片H5 APP

71 阅读1分钟
drawSquarePic(ctx, x, y, w, h, r, url) {
    ctx.save()
    ctx.beginPath()
    // 绘制左上角圆弧
    ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
    // 绘制border-top
    // 画一条线 x终点、y终点
    ctx.lineTo(x + w - r, y)
    // 绘制右上角圆弧
    ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
    // 绘制border-right
    ctx.lineTo(x + w, y + h - r)
    // 绘制右下角圆弧
    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.setFillStyle('#ffffff')
    ctx.fill()
    // 剪切,剪切之后的绘画绘制剪切区域内进行,需要save与restore 这个很重要 不然没办法保存
    ctx.clip()
    // 绘制图片
    return new Promise((resolve, reject) => {
        if (url) {
            uni.getImageInfo({
                src: url,
                success(res) {
                    ctx.drawImage(res.path, x, y, w, h)
                    ctx.restore() //恢复之前被切割的canvas,否则切割之外的就没办法用
                    resolve()
                },
                fail(res) {
                    console.log('fail -> res', res)
                    ctx.drawImage('xx.jpg', x, y, w, h)
                    ctx.restore()
                    resolve()
                }
            })
        } else {
            resolve()
        }
    })
},