anonymoose
anonymoose

Reputation: 1243

How do I restrict an image to another image in fabricjs?

I have a frame image with a transparent center and a button that draws a local image to behind that frame (so it looks framed). How can I confine the uploaded image to the frame? I've tried using a frame image without a transparent surrounding area however I'd eventually like to use backgrounds.

I'm working with different shaped frames that are different sizes. How might I accomplish this? Any help would be greatly appreciated. I've been tinkering with this for days. I'll attach my code and an image to help better show the problem. Thanks in advance!

var canvas = new fabric.Canvas('c');

document.getElementById('file').addEventListener("change", function(e) {
  var file = e.target.files[0];
  var reader = new FileReader();
  reader.onload = function(f) {
    var data = f.target.result;
    fabric.Image.fromURL(data, function(img) {
      var oImg = img.set({
        scaleX: 0.8,
        scaleY: 0.8,
        left: 430,
        top: 65
      })
      canvas.add(oImg);
      canvas.setActiveObject(oImg);
      var image = canvas.getActiveObject();
      image.moveTo(-1);
      canvas.discardActiveObject();
      canvas.renderAll();
    });
  };
  reader.readAsDataURL(file);
});

fabric.Image.fromURL('https://i.imgur.com/OeXL2CJ.png', function(img) {
  var oImg = img.set({
    scaleX: 0.5,
    scaleY: 0.5,
    selectable: false
  })
  canvas.add(oImg).renderAll();
});
canvas {
  border: 1px solid #808080;
  border-radius: 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.min.js"></script>
<input type="file" id="file"><br />
<canvas id="c" width="637" height="412"></canvas>

enter image description here

Upvotes: 1

Views: 903

Answers (2)

Sandor Rozsa
Sandor Rozsa

Reputation: 193

Here you go mate. The quintessence of the answer is the same:

var pug = new fabric.Image(pugImg, {
        width: 500,
        height: 300,
        cropX: 0,
        cropY: 0,
        left: 10,
        top: 10
    });

But maybe it is more comprehensive with a fiddle. And it is a lovely Pug ;-)

http://jsfiddle.net/sharksinn/5vyevd5y/

And please flag as the correct answer if this fixes you problem :-)

Upvotes: 1

Sandor Rozsa
Sandor Rozsa

Reputation: 193

If I understand you right, you would like to show your second image only in the middle area of your frame image. You should be able to do this with the new Fabrc 2 beta. Fabric 2 introduces some new parameters for image onbects: scaleX, scaleY, width, height, cropX, cropY...

Setting the object origin of both images to center/middle and adjusting the width/height and cropX/cropY of your second image should do the trick.

Here is the documentation for the new features:

http://fabricjs.com/v2-breaking-changes#image

Upvotes: 1

Related Questions