4

我正在尝试构建一个自由形式的套索工具来剪辑画布内的图像。我正在使用fabric.js来绘制形状。

var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');

img.onload = function() {
  var OwnCanv = new fabric.Canvas('c', {
    isDrawingMode: true
  });

  OwnCanv.freeDrawingBrush.color = "purple"
  OwnCanv.freeDrawingBrush.width = 4

  ctx.clip();

  ctx.drawImage(img, 0, 0);
}

img.src = "http://upload.wikimedia.org/wikipedia/commons/3/33/Jbassette4.jpg?uselang=fi";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>

<canvas id="c" width="500" height="500"></canvas>

这是我的尝试,似乎不起作用,我在这里做错了什么?

任何人都可以帮助我吗?这将不胜感激。

4

1 回答 1

3

图片必须是fabric.Image.

你可以尝试这样的事情:

var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');

img.onload = function() {
    var OwnCanv = new fabric.Canvas('c', {
        isDrawingMode: true
    });

    var imgInstance = new fabric.Image(img, {
        left: 0,
        top: 0,
    });
    OwnCanv.add(imgInstance);

    OwnCanv.freeDrawingBrush.color = "purple"
    OwnCanv.freeDrawingBrush.width = 4

    OwnCanv.on('path:created', function(options) {
        var path = options.path;
        OwnCanv.isDrawingMode = false;
        OwnCanv.remove(imgInstance);
        OwnCanv.remove(path);
        OwnCanv.clipTo = function(ctx) {
            path.render(ctx);
        };
        OwnCanv.add(imgInstance);
    });
}

img.src = "http://upload.wikimedia.org/wikipedia/commons/3/33/Jbassette4.jpg?uselang=fi";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>

<canvas id="c" width="500" height="500"></canvas>

有关更多信息,请参阅这些资源:

http://fabricjs.com/fabric-intro-part-1/

Fabric.js 画布上的多个剪切区域

Fabric.js 将画布(或对象组)剪辑到多边形

于 2015-04-29T18:30:09.783 回答