Search code examples
javascripthtml5-canvas

Can a js function calling several html canvas draw and drawImage methods be saved into a single Image object?


Can a js function calling several html canvas draw and drawImage methods be saved into a single Image object?

Been searching for a way to do this. I was thinking about utilizing the html canvas clip() method somehow, but no luck as of yet.


Solution

  • You could convert an in-memory canvas to a blob, and then load it into the Image via createObjectURL.

    But depending on your end goal, you might not even need an Image object, for example: you can draw a canvas directly on another canvas' rendering context without needing an intermediary image.

    document.getElementById("btndraw").addEventListener("click", async () => {
      try {
        const img = await drawToNewImage(drawToContext);
        document.getElementById("divtarget")
          .appendChild(img);
      } catch (e) {
        console.error(e);
      }
    });
    
    async function drawToNewImage(drawFn) {
      const canvas = document.createElement("canvas");
      canvas.width = 100;
      canvas.height = 100;
      
      const ctx = canvas.getContext("2d");
      drawFn(ctx);
      const blob = await new Promise(resolve => {
        canvas.toBlob(resolve);
      });
      const img = new Image(100, 100);
      img.src = URL.createObjectURL(blob);
      return img;
    }
    
    function drawToContext(ctx) {
      ctx.strokeStyle = "black";
      ctx.beginPath();
      ctx.moveTo(0, 0);
      ctx.lineTo(100, 100);
      ctx.stroke();
      ctx.beginPath();
      ctx.arc(50, 50, 45, 0, 2 * Math.PI);
      ctx.stroke();
    }
    <button type="button" id="btndraw">Draw</button>
    <div id="divtarget"></div>