为什么我的 canvas 下载为空 PNG?

Why my canvas is downloading as an empty PNG?

我需要你的帮助:)

所以我遵循了有关使用 canvas 制作双色调的教程。 它获取图像,将其转换为灰度,然后再转换为双色调。现在我正在尝试将 canvas 下载为 PNG,但它下载的是一张空图像。

“看起来您的 post 主要是代码;请添加更多详细信息。” 不太确定如何添加更多详细信息:(

知道如何解决吗?

我有点新手。提前致谢

<html>

<head> </head>

<body>
  <div id="main">
    <canvas id="duotone" width="600" height="600"></canvas>
  </div>
  <script>
    function Duotone(id, src, primaryClr, secondaryClr, actions = (ctx) => null) {
      let canvas = document.getElementById(id);
      let ctx = canvas.getContext("2d");

      let downloadedImg = new Image();
      downloadedImg.crossOrigin = "";
      downloadedImg.onload = function() {
        ctx.drawImage(downloadedImg, 0, 0, canvas.width, canvas.height);

        imageData = ctx.getImageData(0, 0, 800, 800);
        const pixels = imageData.data;
        for (let i = 0; i < pixels.length; i += 4) {
          const red = pixels[i];
          const green = pixels[i + 1];
          const blue = pixels[i + 2];
          const avg = Math.round((0.299 * red + 0.587 * green + 0.114 * blue) * 1);
          pixels[i] = avg;
          pixels[i + 1] = avg;
          pixels[i + 2] = avg;
        }
        ctx.putImageData(imageData, 0, 0);
        ctx.globalCompositeOperation = "multiply";
        ctx.fillStyle = primaryClr;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.globalCompositeOperation = "lighten";
        ctx.fillStyle = secondaryClr;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
      };
      downloadedImg.src = src;
    }

    function randomIndex() {
      return Math.floor(Math.random() * 3);
    }

    function randomizeColors() {
      // Arrays of colors, with a random index chosen when clicked.
      let primary = ["#f65e35", "#00ff36", "#77acd4"];
      let secondary = ["#1e3265", "#23278a", "#033dc5"];
      let ind = randomIndex();

      Duotone(
        "duotone",
        "https://i.imgur.com/WQ1Iydl.jpeg",
        primary[ind],
        secondary[ind],
      );
    }

    function downloadImage() {
      document.querySelector("#image").src = document
        .querySelector("#duotone")
        .toDataURL("image/png");
    }
    var canvas = document.getElementById("duotone");
    var image = canvas.toDataURL();
    var aDownloadLink = document.createElement('a');
    aDownloadLink.download = 'canvas_image.png';
    aDownloadLink.href = image;
    aDownloadLink.click();

    randomizeColors();
  </script>
</body>

</html>

您要下载的内容尚未准备好,您需要等待它完全加载。

window.onload = function () {
  var canvas = document.getElementById("duotone");
  var image = canvas.toDataURL();
  var aDownloadLink = document.createElement("a");
  aDownloadLink.download = "canvas_image.png";
  aDownloadLink.href = image;
  aDownloadLink.click();
};