如何在fabricjs中缩放后进行图像转换?

时间:2018-03-10 00:05:03

标签: javascript fabricjs

当图像比例发生变化时,在您点击它之前,它的转换是不可能的。而且,您甚至可以从图像的矩形边界外部移动图像。这很奇怪。

在图像比例改变之后,我应该能够在不点击图像的情况下变换图像。怎么做?

test = function(type){
var obj = activeobj[0].getBoundingRect().height;

if(type === 'fb'){
this.image.set({
  scaleX: 0.5,
  scaleY: 0.5
 });
 canvas.renderAll();
} else {
 this.image.set({
  scaleX: 0.25,
  scaleY: 0.25
 });
 canvas.renderAll();
 }
}

https://jsfiddle.net/hazeebp/2z9yb1nd/43/

1 个答案:

答案 0 :(得分:0)

使用object.setCoords()设置对象的角坐标。

此处已更新fiddle

<强> 样本

&#13;
&#13;
var canvas = this.__canvas = new fabric.Canvas('c');
canvas.setHeight(400);
canvas.setWidth(400);
let image;
// Left Image
fabric.Image.fromURL(`http://www.qygjxz.com/data/out/248/3979080-wallpaper-xperia.png`, (img) => {
  img.set({
    left: 0,
    stroke : 'red',
    strokeWidth : 20,
    id:'wallpaper',
    top: 0
  });
  image = img;
  img.scaleToWidth(300);
  img.scaleToHeight(300);
  canvas.add(img).setActiveObject(img);
})

var activeobj = canvas.getObjects();

test = function(type){
  if(type === 'fb'){
   image.set({
  		scaleX: 0.5,
  		scaleY: 0.5
    });
  } else {
    image.set({
  		scaleX: 0.25,
  		scaleY: 0.25
    });
  }
  image.setCoords();
  canvas.requestRenderAll();
}
&#13;
canvas {
  border: 1px solid #999;
}
&#13;
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<input type="button" value="Plus" onclick="test('fb')">
<input type="button" value="Minus" onclick="test('insta')">
<canvas id="c"> </canvas>
&#13;
&#13;
&#13;