Clip to drawn path

I'm trying to draw a path and them use it as a mask of my canvas.

'use strict';

var canvas = new fabric.Canvas('c', {
    hoverCursor: 'pointer',
    isDrawingMode: true
});

canvas.freeDrawingBrush = new fabric.PencilBrush(canvas);
canvas.freeDrawingBrush.color = '#000';
canvas.freeDrawingBrush.width = 100;

fabric.Image.fromURL('http://fabricjs.com/assets/pug_small.jpg', function(img) {

    canvas.add(img);
    canvas.setWidth(img.getWidth());
    canvas.setHeight(img.getHeight());
    canvas.centerObject(img);
    img.selectable = false;
});

canvas.on('path:created', function(data) {

    var path = data.path;

    canvas.remove(path);
    canvas.clipTo = function(context) {
        path.render(context);
    };

    canvas.isDrawingMode = false;
    canvas.renderAll();
});

How can I make the entire path be the visible area of my image?

http://jsfiddle.net/db45yhpo/

EDIT

This is what I'm trying to achieve, but using FabricJS.

http://www.createjs.com/demos/easeljs/alphamaskreveal


I have no experience with fabricjs, so there may be a better way of handling this but I would :
Redraw your path on an hidden canvas,
Then create a new fabric.Image() from this hidden canvas,
Set its globalCompositeOperation parameter to `"destination-atop",
Draw it on the original canvas.

var canvas = new fabric.Canvas('c', {
  hoverCursor: 'pointer',
  isDrawingMode: true
});

canvas.freeDrawingBrush = new fabric.PencilBrush(canvas);
canvas.freeDrawingBrush.color = '#000';
canvas.freeDrawingBrush.width = 100;

fabric.Image.fromURL('http://fabricjs.com/assets/pug_small.jpg', function(img) {
  canvas.add(img);
  canvas.setWidth(img.getWidth());
  canvas.setHeight(img.getHeight());
  canvas.centerObject(img);
  img.selectable = false;
});

canvas.on('path:created', function(data) {
  var clipper = document.createElement('canvas');
  clipper.width = canvas.width;
  clipper.height = canvas.height;
  var ctx = clipper.getContext('2d');
  var path = data.path;
  data.path.render(ctx);
  canvas.remove(path);
  canvas.isDrawingMode = false;
  var oImg = new fabric.Image(clipper)
  oImg.globalCompositeOperation = 'destination-atop';
  canvas.add(oImg);
  canvas.renderAll();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<canvas id="c"></canvas>
链接地址: http://www.djcxy.com/p/29708.html

上一篇: 使用ManyToOne引用嵌入的Spring数据序列化

下一篇: 剪切到绘制路径