js 将多张图片合并成一张图片

废话不多说,直接上代码

<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      function mergeImgs(list, cwith = 500, cheight = 1000) {
        return new Promise((resolve, reject) => {
          const baseList = [];
          // 创建 canvas 节点并初始化
          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]) {
                // 返回新的图片
                resolve(baseList[list.length - 1]);
              }
            };
          });
        });
      }
      const urlList = ['./images/1.jpg', './images/2.jpg', './images/3.jpg'];
      mergeImgs(urlList).then((base64) => {
        const imgDom = document.createElement('img');
        imgDom.src = base64;
        document.body.appendChild(imgDom);
      });
    </script>
  </body>
</html>

你可能感兴趣的:(js基础,前端)