Draw an image in a form using Fabricjs

I am currently working on image processing in canvas and Javascript. I use the fabric.js file for this. I just want the user to upload the image and combine it with the template we provided. i.e.

the Template

I want to show the downloaded image only in an empty circle in the center, and they can be customized by dragging it.

  • If I save the template as the top level, the user cannot drag and customize, since the canvas is filled with the template.
  • If I save the loaded image as the top layer, then the image will overflow the circle.

How can I solve this problem by providing the user with a convenient interface? I tried using ClipTo in the fabric.js file, but it does not work with the image object.

+7
source share
3 answers

I think overlayImage is what you need.

See a demo of the setup , for example:

Example of overlayImage

var canvas = new fabric.Canvas('c13'); var circle = new fabric.Circle({ radius: 30, fill: '#f55', top: 100, left: 100 }); canvas.add(circle); canvas.setOverlayImage('../assets/jail_cell_bars.png', canvas.renderAll.bind(canvas)); 
+5
source

You can draw both a photograph and a template in canvas. I'm not sure about fabric.js, but if you called canvas functions directly, you just ...

 ctx = canvas.getContext('2d'); ctx.DrawImage(user_img, x,y); ctx.DragImage(template_imb, 0, 0); 

When the user drags the mouse update x and y and redraws both layers. Obviously, make sure that the hole in the template is transparent. You can add width and height to the DrawImage call if you want the user to be able to resize the image, just provide some kind of control to resize them.

+1
source

A more complicated method is to create a temporary (off-screen) canvas. Using globalCompositeOperation=source-in , draw an image from the mask image, then getImageData from there and putImageData to your destination port.

But if Charlesโ€™s answer works for you, itโ€™s much easier.

0
source

All Articles