在结构JS中对象缩放的模式重复

时间:2013-09-11 07:08:39

标签: design-patterns html5-canvas repeat fabricjs tiling

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

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

现在缩放它时会缩放。

由于

1 个答案:

答案 0 :(得分:1)

@ 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/