I'm trying to implement a feature in my canvas using fabricjs that will allow me to zoom in/out an individual image thats been uploaded by a user and the watermark which I'm adding with it but not having the WHOLE canvas zoom both objects at the same time.
uploadImage = event => {
let file = event.target.files[0];
this.state.canvas.clear();
let URL;
const reader = new FileReader();
reader.addEventListener(
"load",
() => {
URL = reader.result;
fabric.Image.fromURL(URL, myImg => {
let img1 = myImg.set({
left: 0,
top: 0,
width: 500,
height: 500
});
this.state.canvas.add(img1);
});
},
false
);
if (file) {
reader.readAsDataURL(file);
}
fabric.Image.fromURL("watermark.jpeg", oImg1 => {
oImg1.set({
left: 0,
top: 0,
width: 500,
height: 100,
centeredScaling: true,
hasControls: false,
lockMovementX: true,
lockMovementY: true,
hasControls: false
});
this.state.canvas.add(oImg1);
this.state.canvas.renderAll();
});
this.state.canvas.on("mouse:wheel", opt => {
const delta = opt.e.deltaY;
const pointer = this.state.canvas.getPointer(opt.e);
let zoom = this.state.canvas.getZoom();
zoom = zoom + delta / 200;
if (zoom > 20) zoom = 20;
if (zoom < 0.01) zoom = 0.01;
this.state.canvas.zoomToPoint(
{ x: opt.e.offsetX, y: opt.e.offsetY },
zoom
);
opt.e.preventDefault();
opt.e.stopPropagation();
});
};
I've tried going through the fabricjs docs but they don't make a great deal of sense to me.
It's supposed to zoom each image separately instead of the whole canvas.
Yes I know its bad code and probably doesn't follow convention, I'm new to react/javascript/programming in general.
It is quite easy to scale objects individually, check my fiddle where you can hover the image and zoom it by mouse wheel: http://jsfiddle.net/mmalex/q1m8t2gp/
The key point is to subscribe on mousewheel
event on each image object separately. Secondly, you would need to re-center image and not forget to run canvas.renderAll();
in the end.
oImg.on('mousewheel', function(options) {
var scrollDirection = options.e.deltaY > 0 ? -1 : 1;
// on what object it was scrolled?
let target = canvas.findTarget(options.e.target);
//updates image scale by +/- 5%
var marioScale = target.scaleX;
marioScale += scrollDirection * 0.05;
var scaledWidth = target.getScaledWidth();
var scaledHeight = target.getScaledHeight();
//remember where was the center of the image
var oldCenter = new fabric.Point(
target.left + scaledWidth / 2,
target.top + scaledHeight / 2);
target.scale(marioScale);
//after scale center moved, we need to re-center back to old center
var newScaledWidth = target.getScaledWidth();
var newScaledHeight = target.getScaledHeight();
target.left = oldCenter.x - newScaledWidth / 2;
target.top = oldCenter.x - newScaledHeight / 2;
canvas.renderAll();
});
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.