我正在尝试画一条路径,然后用它作为我画布的面具。
'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();
});
如何让整个路径成为我图像的可见区域?
修改
这是我想要实现的,但使用FabricJS。
答案 0 :(得分:3)
我没有使用fabricjs的经验,所以可能有更好的方法来处理这个问题,但我会:
在隐藏的画布上重绘您的路径,
然后从这个隐藏的画布中创建一个新的fabric.Image(),
将其globalCompositeOperation
参数设置为“" destination-atop",
在原始画布上绘制。
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>
&#13;