使用Fabricjs填充拉伸图像的矩形

时间:2016-02-07 00:45:27

标签: html5-canvas fabricjs

我创建了一个使用Fabricjs绘制矩形的代码,并使用图像模式和“无重复”填充矩形。这是代码:

<!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>

如何用拉伸图像填充矩形?

1 个答案:

答案 0 :(得分:1)

虽然在我的回答中我没有使用模式的概念,但我希望它能帮到你。

        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';