简体   繁体   中英

Setting background image in canvas (fabric js)

Goal is to set up a canvas on top of an image. (Making product mockup generator like teespring has, but simpler)

Codepen : https://codepen.io/anon/pen/YmEGyW

I have gotten this almost to where I would like it but I have a few issues:

If I set the background image on the canvas, I am unable to save (not sure why but when i do this i can't click "save", nothing happens). Like so:

const canvas = new fabric.Canvas('fCanvas', {
  backgroundImage: "https://drive.google.com/uc?export=view&id=0B3ubyt3iIvkaUlpHVEpDTGhjQzg",
...
});

To fix this, I create a canvas on a canvas... But this only works when I upload an image (or how i figured out how to make it work, so far, like in the codepen example)

What I would like is to have a background image pre loaded instead of needing to upload a background image.

How can I have the google drive image loaded on load (down below) without needing to upload through the input/form?

In practice, this will dynamically but for now I would like to use "https://drive.google.com/uc?export=view&id=0B3ubyt3iIvkaUlpHVEpDTGhjQzg" for the background image. Then be able to upload the scalable image on top.

I would suggest you to use css for setting background image.

Solution #1

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.0.0-beta.7/fabric.min.js"></script>

<div>
  <canvas id="fCanvas" width="400" height="400"></canvas>
</div>
<a id="downloadLnk" download="YourFileName.jpg">Download as image</a>

JS

const canvas = new fabric.Canvas('fCanvas');
fabric.Image.fromURL('https://picsum.photos/id/1083/200/300', 
    function(img) {
        canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas), {
          scaleX: canvas.width / img.width,
          scaleY: canvas.height / img.height
        });
    }, { crossOrigin: 'Anonymous' });

function download() {
   var dt = canvas.toDataURL('image/jpeg');
   this.href = dt;
};
downloadLnk.addEventListener('click', download, false);

Codepen

https://codepen.io/murli2308/pen/XvzzWz

Solution #2

CSS

canvas {
    background: url(https://picsum.photos/id/1083/200/300);
}

You can replace CSS selector with class or id. Also, you can add background-size and background-position according to your requirement.

looking at the docs here the options which made it work for me are not shown.

var canvas = new fabric.Canvas('canvas-id');

canvas.setBackgroundImage('https://......', canvas.renderAll.bind(canvas), {
    backgroundImageOpacity: 1,
    backgroundImageStretch: false
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM