解决方案
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
function mergeImgs(list) { const imgDom = document.createElement( 'img' ) document.body.appendChild(imgDom) const canvas = document.createElement( 'canvas' ) canvas.width = 500 canvas.height = 500 * list.length const context = canvas.getContext( '2d' ) list.map((item, index) => { const img = new Image() img.src = item // 跨域 img.crossOrigin = 'Anonymous' img.onload = () => { context.drawImage(img, 0, 500 * index, 500, 500) const base64 = canvas.toDataURL( 'image/png' ) imgDom.setAttribute( 'src' , base64) // console.log(baseList) } }) } const urlList = [ './img/timg%20(1).jpg' , './img/timg.jpg' ] mergeImgs(urlList ) |
代码稍微优化一下,改成公共方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
/** * 合并多张图片,返回新的图片 * @param {Array} list 图片url数组 * @param {Number} cwith 画布宽度 默认500 * @param {Number} cheight 画布高度 默认500 */ function mergeImgs(list, cwith = 500, cheight = 500) { return new Promise((resolve, reject) => { const baseList = [] const canvas = document.createElement( 'canvas' ) canvas.width = cwith canvas.height = cheight * list.length const context = canvas.getContext( '2d' ) list.map((item, index) => { const img = new Image() img.src = item // 跨域 img.crossOrigin = 'Anonymous' img.onload = () => { context.drawImage(img, 0, cheight * index, cwith, cheight) const base64 = canvas.toDataURL( 'image/png' ) baseList.push(base64) if (baseList[list.length - 1]) { console.log(baseList) // 返回新的图片 resolve(baseList[list.length - 1]) } } }) }) } const urlList = [ './img/timg%20(1).jpg' , './img/timg.jpg' ] mergeImgs(urlList ).then(base64 => { const imgDom = document.createElement( 'img' ) imgDom.src = base64 document.body.appendChild(imgDom) }) |
效果
到此这篇关于js使用Canvas将多张图片合并成一张的实现代码的文章就介绍到这了,更多相关js canvas图片合并一张内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/weixin_45337170/article/details/115318940