Reputation: 332
I have an image on a canvas using FabricJS, after I load the image I call canvas.centerObject(img). I have the same image scaled 2X, I am trying to imaplement a Magnify Glass functionality, everything works fine without centering the image, but as soon as I call canvas.centerObject(img) the bigger image doesn't show in the rigth position.
fabric.Image.fromURL('http://fabricjs.com/assets/pug_small.jpg', function (img) {
img1 = img;
img.set({
width: originalWidth,
height: originalHeight,
evented: true,
selectable: false
});
lens = fabric.util.object.clone(img);
lens.set({
width: scale * originalWidth,
height: scale * originalHeight,
clipTo: function (ctx) {
ctx.arc(-this.left + x - this.width / 2, -this.top + y - this.height / 2, radius, 0, Math.PI * 2, true);
}
});
canvas.add(img, lens);
canvas.centerObject(img);//*******issue here****
});
canvas.on('mouse:move', function (e) {
x = e.e.layerX;
y = e.e.layerY;
lens.set('left', -(scale - 1) * x);
lens.set('top', -(scale - 1) * y);
canvas.renderAll();
});
Thanks.
Upvotes: 0
Views: 2116
Reputation: 2407
I re-aligned the bigger image so it shows correctly when you call canvas.centerObject(img)
. However, you might like to rethink your design a little to perhaps incorporate object scaling, scale()
- depending on your implementation needs, of course.
Here's an updated JSFiddle and the tweaked code:
https://jsfiddle.net/rekrah/rfdxff5h/
fabric.Image.fromURL('http://fabricjs.com/assets/pug_small.jpg', function(img) {
img1 = img;
img.set({
width: originalWidth,
height: originalHeight,
evented: true,
selectable: false
});
lens = fabric.util.object.clone(img);
lens.set({
top: -225,
left: 150,
width: scale * originalWidth,
height: scale * originalHeight,
clipTo: function(ctx) {
ctx.arc(-this.left + x - this.width / 2, -this.top + y - this.height / 2, radius, 0, Math.PI * 2, true);
}
});
canvas.add(img, lens);
canvas.centerObject(img);//******* issue no longer here****
});
canvas.on('mouse:move', function(e) {
x = e.e.layerX;
y = e.e.layerY;
if (x > 150 && x < 750) {
lens.set('left', -(scale - 1) * x + 300);
lens.set('top', -(scale - 1) * y);
}
canvas.renderAll();
});
Upvotes: 1