canvas 图片合并(1)
<pre><code class="language-javascript">/**
* 合并四张图为一张
* @param {*} imgList
* @param {*} width
* @param {*} height
* @returns
*/
export async function mergeCanvas4(imgList, width, height) {
return new Promise((resolve, reject) =&gt; {
// 创建 canvas 节点并初始化
const canvas = document.createElement('canvas');
canvas.width = width * 2 + 8; // 间隔8像素
canvas.height = height * 2 + 8; // 间隔8像素
const context = canvas.getContext('2d');
let count = 0;
imgList.forEach((item, index) =&gt; {
const img = new Image();
img.src = item;
// 跨域
img.crossOrigin = 'Anonymous';
img.onload = () =&gt; {
index === 0 &amp;&amp; context.drawImage(img, 0, 0, width, height);
index === 1 &amp;&amp; context.drawImage(img, width + 8, 0, width, height);
index === 2 &amp;&amp; context.drawImage(img, 0, height + 8, width, height);
index === 3 &amp;&amp; context.drawImage(img, width + 8, height + 8, width, height);
count++;
if (count === imgList.length) {
resolve(canvas.toDataURL('image/jpeg'));
}
};
});
});
}</code></pre>