关于javascript:html使用canvas合并多张图片并下载

33次阅读

共计 1420 个字符,预计需要花费 4 分钟才能阅读完成。

html 应用 canvas 合并多张图片并下载

html 应用 canvas 合并多张图片并下载

1. 创立 canvas 对象,并引入 2d 上下文实例

const canvas = document.createElement('canvas')
let ctx = canvas.getContext('2d');
canvas.width = 1920 // 设定 canvas 的宽度、高度
canvas.height = 1080

2. 创立图片对象

let img1 = new Image();
img1.src = require('../../assets/img/monitor/map-name.png');
// 监听 onload 事件,待图片加载结束后绘制到 canvas 上
// 计数器,用来计数是否全副加载实现
let num = 0
img1.onload = function() {ctx.drawImage(img1, 10, 10);
    // 假如 img1 是必须先退出,则其余图片在其 onload 函数上加载并绘制到 canvas
    let img2 = new Image();
    img2.src = require('../../assets/img/monitor/map-name.png');
    let img3 = new Image();
    img3.src = require('../../assets/img/monitor/boundary.png');
    // 别离监听 img2 和 img3 的 onload 事件
    img1.onload = function() {ctx.drawImage(img1, 10, 10);
        num++
        if (num === 2) { // 判断是否是最初一张,是最初一张则下载图片
            // 将 canvas 转化成 URL 链接,用 a 标签进行下载或者预览,img 标签预览都能够
            href = canvas.toDataURL();
            const downloadElement = document.createElement('a')
            downloadElement.href = href
            downloadElement.target = '_blank'
            downloadElement.download = `${name}.png`
            document.body.appendChild(downloadElement)
            downloadElement.click()
            document.body.removeChild(downloadElement)
        }
    }
    img3.onload = function() {ctx.drawImage(img3, 10, 10);
        num++
        if (num === 2) {href = canvas.toDataURL();
            const downloadElement = document.createElement('a')
            downloadElement.href = href
            downloadElement.target = '_blank'
            downloadElement.download = `${name}.png`
            document.body.appendChild(downloadElement)
            downloadElement.click()
            document.body.removeChild(downloadElement)
        }
    }
})
注:思路就是将图片依照你想要的程序增加到 canvas 的指定地位,而后待全副加载实现后采纳 a 标签下载下来,本地链接,内部链接,blob 流都实用

正文完
 0