最近写公司项目遇到了这个fabirc这个库,第一次使用这个库可谓是遇到了很多麻烦,不过还好经过多天熬夜奋斗才勉强熟练使用这个库,今天小编初略的说一下怎么对图片进行等比缩放。话不多说直接看代码注释
let that = this;
//创建图片画布
fabric.Image.fromURL(
imgurl, // 图片路径
img => {
this.datapotoimg = img;
img.scale(0.2);
img.customId = id; //用于标识
img.Tpe = "panelSZR";
img.set(
{
originX: "center",//图片原点居中
originY: "center"//图片原点居中
},
{ crossOrigin: "anonymous" }//解决跨域问题
);
img.on("scaling", function(e) {//拉伸事件
let h = img.scaleY;
let w = img.scaleX;
if (h !== w || w == h) {//判断缩放值相等或不相等后执行图片等比缩放
if (e.e.movementY == -1 || e.e.movementY == 1) {
img.scale(h);//缩放
that.querSZR("opcion", h);
let left = img.left - (img.width * h) / 2;
let top = img.top - (img.height * h) / 2;
// let bottom =450-img.top - (img.height * w) / 2;
that.querSZR("location1", top);
that.querSZR("location2", left);
} else {
img.scale(w);缩放
that.querSZR("opcion", w);
let left = img.left - (img.width * w) / 2;
let top = img.top - (img.height * w) / 2;
that.querSZR("location1", top);
that.querSZR("location2", left);
}
}
});
img.setCoords();
img.centeredScaling = true;//配合以上操作
img.centerTransform = true;//配合以上
this.canvas.add(img);
this.canvas.centerObject(img);//图片居中显示
this.canvas.renderAll();//重新加载
}
);