将 Canvas 元素转换为图像元素

Convert a Canvas element into Image element

我有一个网站,我需要在其中生成特定于用户的动态图像。我发现的方法是使用 canvas。我有文本信息和图像文件需要复制到canvas,然后,稍后可以转换为用户可以下载的图像文件。

function generateImage() {
    let event_date = '11-02-2022'
    let event_name = 'Prom Night'

    let canvas = document.getElementById("your-canvas")
    let ctx = canvas.getContext("2d")

    ctx.font = "26px Arial";
    ctx.textAlign = 'center'

    // For Heading
    ctx.fillText(event_date + ' - ' + event_name, 400, 50)

    var img = new Image();
    img.onload = function () {
        ctx.drawImage(img, 100, 100);
    }
    img.src = 'https://cdn.sstatic.net/stackexchange/img/logos/so/so-icon.png'
    return canvas.toDataURL('image/jpg')
}

// generateImage()
let image_gen = generateImage()
$('#gen-image').attr('src', image_gen)
<script src="https://code.jquery.com/jquery-3.6.0.js"
        integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>

<center>
  <h1>CANVAS ELEMENT</h1>
</center>
<br>
<canvas id="your-canvas" width="1000" height="400"></canvas>
<center>
  <h1>IMAGE ELEMENT</h1>
</center>
<br>
<img src="" id="gen-image" alt="" style="border: 0.1em solid black;">

正如您在代码片段中看到的那样,图像是可见的并已成功复制到 canvas 中,但当 canvas 转换为 img 时不可见 toDataURL()

加载图像可能需要一些时间。在您的代码中,toDataURL 在加载图像并在 canvas 上绘制之前返回 toDataURL

为了解决这个问题,可以使用Promise等到图片加载完毕,然后获取canvas的URL .

function generateImage() {
  const promise = new Promise((resolve, reject) => {
    let event_date = "11-02-2022";
    let event_name = "Prom Night";

    let canvas = document.getElementById("your-canvas");
    let ctx = canvas.getContext("2d");

    ctx.font = "26px Arial";
    ctx.textAlign = "center";

    // For Heading
    ctx.fillText(event_date + " - " + event_name, 400, 50);

    var img = new Image();
    img.setAttribute("crossorigin", "anonymous");
    img.src = "https://picsum.photos/200/300";
    img.onload = () => {
      ctx.drawImage(img, 100, 100);
      resolve(canvas.toDataURL("image/jpg"));
    };
  });
  return promise;
}

generateImage().then((value) => {
  $("#gen-image").attr("src", value);
});
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>

<center>
  <h1>CANVAS ELEMENT</h1>
</center>
<br>
<canvas id="your-canvas" width="1000" height="400"></canvas>
<center>
  <h1>IMAGE ELEMENT</h1>
</center>
<br>
<img src="" id="gen-image" alt="" style="border: 0.1em solid black;">