canvas 图片组合并进行下载

50 阅读1分钟

运行图片:

在这里插入图片描述

思路:先画一个背景图片,再画一个二维码定位到你想要的位置,最后直接下载即可,可以扩散一下思维,画简单的海报的时候,也可以的

源代码


<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
  </style>
</head>

<body>

</body>

</html>

<script>
  // 初始化
  const init = async (tasks) => {
    // 创建画布
    const canvas = document.createElement('canvas');
    document.body.appendChild(canvas);
    const width = tasks?.otherOptions?.canvasWidth || 280;
    const height = tasks?.otherOptions?.canvasHeight || 400;
    canvas.width = width;
    canvas.height = height;
    canvas.style.width = `${width}px`;
    canvas.style.height = `${height}px`;
    const ctx = canvas.getContext('2d');
    for (const task of tasks?.imgOptions) {
      await drawImage(ctx, task);
    }
    downloadCanvas(ctx, tasks?.otherOptions?.downloadName,tasks?.otherOptions?.type)

  }
  // 下载图片
  function downloadCanvas (ctx, name, type = 'image/png') {
    // 创建一个下载链接
    const link = document.createElement('a');
    // 将 canvas 转换为图片 URL
    const imageUrl = ctx.canvas.toDataURL(type);
    link.download = name;  // 设置下载文件名
    link.href = imageUrl;
    link.style.display = 'none';
    document.body.appendChild(link);
    // 触发下载
    link.click();
    document.body.removeChild(link);
  }
  // 绘制图片
  function drawImage (ctx, options) {
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.src = options.url;
      img.onload = function () {
        const width = options.width || img.width;
        const height = options.height || img.height;
        ctx.drawImage(img, options.x, options.y, width, height);
        const imageData = ctx.getImageData(options.x, options.y, width, height);
        resolve(imageData);
      }
      img.onerror = function () {
        reject(new Error('Failed to load image'));
      }
    })
  }

  // 任务
  const tasks = {
    imgOptions: [
      {
        url: './bg.png',
        x: 0,
        y: 0,
        width: 300,
        height: 400
      },
      {
        url: './erweima.png',
        x: 70,
        y: 40,
        width: 130,
        height: 180
      }
    ],
    otherOptions: {
      canvasWidth: 280,
      canvasHeight: 400,
      downloadName: '骑车啦.png',
      type: 'image/png'
    }
  }
  init(tasks);
</script>