3
Is there any way to repeat the pattern inside an object in fabric JS.

假设我有一个填充有图案的矩形。我希望在缩放矩形时重复该模式。

现在当我缩放它时它正在缩放。

谢谢

4

1 回答 1

2

@user2571818 我也在寻找这个,终于让它工作了。我们必须使用object:scaling事件将对象缩放回 1x 并更改对象的大小,以使模式重复而不是缩放它。看这里

var canvas = new fabric.Canvas('c');
fabric.Object.prototype.transparentCorners = false;

  var padding = 0;

  fabric.Image.fromURL('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAIAAACRXR/mAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAASdEVYdFNvZnR3YXJlAEdyZWVuc2hvdF5VCAUAAADLSURBVFhH7ZnBCoMwEET9/68URBHSNj0UolFoI+aQickKlT05jz0MGQIPkb2kadu3ta42ff/MTtLRazct55bajOMjO0lHr920vnWMMTGV0GuphVALoRaiqNV1dq4TLsdUIrTe+z0fw+ndmEo0w/D61AmXYyqh1179WjGVuNLyl0eohVALuZ8Wtzwgt9zyiNxSC6EWQi1EUYtbHpBbbnlEbqmFUAuhFqKoxS0PyC23PCK31EKohVAL0dXK3vLSOX0TnKZ1z8fw/3uiW37L27QIZwrV4gAAAABJRU5ErkJggg==', function(img) {

    img.scaleToWidth(50);
    var patternSourceCanvas = new fabric.StaticCanvas();
    patternSourceCanvas.add(img);
    patternSourceCanvas.renderAll();
    var pattern = new fabric.Pattern({
      source: function() {
        patternSourceCanvas.setDimensions({
          width: img.getScaledWidth() + padding,
          height: img.getScaledHeight() + padding
        });
        patternSourceCanvas.renderAll();
        return patternSourceCanvas.getElement();
      },
      repeat: 'repeat'
    }); 

    var rect = new fabric.Rect({
        width: 250,
        height: 250,
        fill: pattern,
        objectCaching: false
    });

    canvas.add(rect);
    rect.center().setCoords();

 });



canvas.on('object:scaling', function(e) {
  if (e.target != null) {
    console.log(e.target);
    var obj = e.target;
        var height = obj.height * obj.scaleY;
        var width = obj.width * obj.scaleX;
        obj.height = height;
        obj.width = width;
        obj.scaleX = 1;
        obj.scaleY = 1;
  }
});

JSFiddle: https ://jsfiddle.net/dotriz/ajsdmg4s/

于 2017-09-12T14:25:50.103 回答