imgCanavs.js 3.03 KB
let canvasRef = null
let ctx = null


export function dataInfo(deg, url) {
    return new Promise((resolve, reject) => {
        if (document.getElementById("imgViewCanvas")) {
            canvasRef = document.getElementById("imgViewCanvas")
            ctx = canvasRef.getContext('2d')
            deg = deg
            initCanvas(deg, url).then(res => {
                resolve(res)
            })
        }
    })
}

function getRotateParams(deg, width, height) {
    const x =
        (width / 2) * Math.cos((Math.PI * deg) / 180) +
        (height / 2) * Math.sin((Math.PI * deg) / 180) -
        width / 2
    const y =
        (Math.cos((Math.PI * deg) / 180) * height) / 2 -
        (Math.sin((Math.PI * deg) / 180) * width) / 2 -
        height / 2
    return {
        x,
        y
    }
}
function initCanvas(deg, url) {
    return new Promise((resolve, reject) => {
        if (ctx) {
            const img = document.createElement('img')
            img.crossOrigin = "Anonymous"
            img.src = url
            img.onload = () => {
                if (deg == 90 || deg == 270) {
                    canvasRef.width = img.height
                    canvasRef.height = img.width
                } else if (deg == 180) {
                    canvasRef.width = img.width
                    canvasRef.height = img.height
                }
                const imgAspectRatio = img.height / img.width
                const imgWidth = img.width
                const imgHeight = imgWidth * imgAspectRatio
                const { x, y } = getRotateParams(deg, canvasRef.width, canvasRef.height)
                ctx?.rotate((deg * Math.PI) / 180)
                ctx?.translate(x, y)
                ctx?.drawImage(
                    img,
                    (canvasRef.width - imgWidth) / 2,
                    (canvasRef.height - imgHeight) / 2,
                    imgWidth,
                    imgHeight,
                )
                // canvasRef.toDataURL('image/jpeg', 0.5)
                canvasRef.toBlob((blob) => {
                    resolve(blob)
                    // const aLink = document.createElement('a')
                    // aLink.href = URL.createObjectURL(blob)
                    console.log(URL.createObjectURL(blob))
                    // aLink.setAttribute('download', 'xxxx') // 设置下载文件名称
                    // document.body.appendChild(aLink)
                    // aLink.click()
                    // document.body.removeChild(aLink);
                    ctx.fillRect(0, 0, 0, 0)
                }, 'image/jpeg', 0.9)
            }
        }
    })
}


// // 0. 获取到页面上的 canvas 标签元素节点
// const canvasEle = document.querySelector('#canvas')

// // 1. 获取当前这个画布的工具箱
// const ctx = canvasEle.getContext('2d')

// // 2. 加载图片
// myImg.sec = './01小锋.png'
// // 准备一个加载完毕的事件
// myImg.onload = function () {
//     console.log(this) // 这里的 this 就是这个图片的内容

//     // 3. 插入到画布内
//     ctx.drawImage(this, 100, 100, 236, 368)
// }