Search code examples
canvashtml5-canvasfabricjs

Fabric JS - Can i save canvas as image but with background from <img> tag?


I put the canvas element in the div and the img element for the background. Of course I can use canvas.toDataURL('image/png'), but that only saves all objects that are inside the canvas element, I want to save everything in div id="custom-cloth" as image, how to do this?

for example code

<div id="custom-cloth">

        <!-- Tshirt Image -->
        <div class="w-full h-[38rem] overflow-hidden">
            <img id="img" src="http://sakaw.test/storage/editor/depan.png" class="mx-auto"> <--- Here is the background
        </div>

        <!-- Canvas -->
        <div
            class="absolute top-20 inset-x-0 w-[17rem] h-[30.5rem] mx-auto border-2 border-dashed border-transparent rounded-lg hover:border-orange-500">
            <canvas id="c"></canvas>
        </div>

    </div>

Output code displayed

Screenshot

sorry I'm not good at explaining


Solution

  • Assuming your end objective is to convert dom to an image. May be you could try out dom-to-image https://github.com/tsayen/dom-to-image

    domtoimage.toJpeg(document.getElementById('my-node'), { quality: 0.95 })
        .then(function (dataUrl) {
            var link = document.createElement('a');
            link.download = 'my-image-name.jpeg';
            link.href = dataUrl;
            link.click();
        });
    

    Here is the codesandbox demo https://codesandbox.io/s/dom-node-to-png-10odz2