setPattern examples

Used in documentation (jsdoc tag)

by Balázs Baumgartner

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.4.3/fabric.min.js"></script>
<canvas id="c" width="400" height="400"></canvas>

CSS

#c {
    border: 1px solid #999;
}

Babel + JSX

const woodPattern = 'https://fchbackend.cheppers.com/sites/default/files/photos/578.png?zvi41q';

// Fabric initializing
fabric.Object.prototype.set({
  transparentCorners: false,
  cornerSize: 12,
});

const canvas = window._canvas = new fabric.Canvas('c');

const doorShape = new fabric.Rect({
  width: 1200,
  height: 2000,
  stroke: 'red',
  strokeWidth: 1,
  fill: '#29477F',
});

fabric.util.loadImage(woodPattern, function (img) {
  doorShape.setPatternFill({
    source: img,
    repeat: 'no-repeat'
  });
  canvas.renderAll();
});

doorShape.scale(0.15);
canvas.add(doorShape);
doorShape.center().setCoords();


/*

fabric.util.addListener(document.getElementById('toggle'), 'click', function () {
    var obj = canvas.item(0);

    if (!obj.fill instanceof fabric.Pattern) return;
    
    obj.fill.repeat = obj.fill.repeat === 'repeat' 
        ? 'repeat-x'
        : obj.fill.repeat === 'repeat-x'
            ? 'repeat-y'
            : obj.fill.repeat === 'repeat-y'
                ? 'no-repeat'
                : 'repeat';

    canvas.renderAll();
});
*/