Hendri Tobing
Hendri Tobing

Reputation: 371

Fill rectangle with stretched image with Fabricjs

I have created a code for drawing a rectangle by using Fabricjs and fill the rectangle with an image pattern and with 'no-repeat'. Here is the code:

<!DOCTYPE HTML>
<html>
<head>
  <script src="js/fabric.min.js" ></script>
</head>
<body>

<script>
function addRect() {
  var canvas = new fabric.Canvas('c');
  fabric.Object.prototype.transparentCorners = false;

    canvas.setWidth(800);
    canvas.setHeight(600);

  function loadPattern(url) {
    fabric.util.loadImage(url, function(img) {
      rect.fill = new fabric.Pattern({
        source: img,
        repeat: 'no-repeat',
      });
      canvas.renderAll();
    });
  }

 rect = new fabric.Rect({
                left: 100,
                top: 100,
                width: 200,
                height: 200,
                angle: 0,
                stroke: 'red',
                strokeWidth: 3,
            });

            canvas.add(rect);


  loadPattern('images/test.png');

  document.getElementById('fillpattern').onchange = function() {
    loadPattern('images/' + this.value+'.png');
  };
  canvas.renderAll();
  }


</script>
<button onclick="addRect()">add</button>
<select id="fillpattern" name="fillpattern">
                              <option value="horizontal">horizontal</option>
                              <option value="vertical">vertical</option>
                              <option value="diagonal">diagonal</option>
                              <option value="cross">cross</option>
                              <option value="test">test</option>
                            </select>

<div>
     <canvas id="c">
     </canvas>
</div>

</body>
</html>

How could I fill the rectangle with a stretched image?

Upvotes: 1

Views: 2939

Answers (1)

Libretto
Libretto

Reputation: 21

Although in my answer I am not using the concept of the pattern but I hope it will help you.

        var canvas = new fabric.Canvas('c');
        var ctx = canvas.getContext("2d");
        ctx.beginPath();     
        ctx.rect(40, 40, 220, 220);
        ctx.closePath();
        ctx.stroke();
        ctx.clip();
        var img = new Image();
        img.onload = function () {
            var img_ = new fabric.Image(img, {
                left: 20,
                top: 0,
                height: 220,
                width: 220,
                selectable: true,
                hasControls: false,
                hasBorders: false
            });
            canvas.add(img_);
            img_.sendToBack();
        };
        img.src = 'images/87357.jpg';

Upvotes: 2

Related Questions