Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw image within a shape using Fabricjs

I am currently working on image manipulation in canvas and Javascript. I am using fabric.js for it. I just want the user to upload an image and merge it with the template provided by us. ie.,

the Template

I want to show the uploaded image only in the empty circle in the center and they can adjust by dragging it.

  • If I keep the template as upper layer the user can't drag and adjust since the canvas is filled with template.
  • If I keep uploaded image as the upper layer then the image will overflow the circle.

How can I solve this by giving my user an easy to use interface? I tried for ClipTo function in fabric.js but it doesn't work with image Object.

like image 974
RSK Avatar asked Dec 03 '11 11:12

RSK


2 Answers

I think overlayImage is what you're after.

Take a look at customization demo 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));
like image 69
kangax Avatar answered Sep 20 '22 22:09

kangax


You could draw both the photo and the template into the canvas. I'm not sure about fabric.js, but if you called the canvas functions directly you would simply...

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 redraw both layers. Obviously make sure 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 the change them.

like image 32
Charles Avatar answered Sep 16 '22 22:09

Charles