让我向您展示我的想法,当您将图像放入路径时,此路径可能是其基于过滤器的参数,如果您想移动路径及其内部的所有内容,我认为使用组是一种方式。实际上,此图像不在路径内,但看起来确实如此。我真的希望fabricjs可以有另一个对象的子树,所以对象的每个孩子只能在这个对象内活动,但显然这个想法不适合当前版本。我想做一个,还在学习fabric.js源码。http://jsfiddle.net/hellomaya/kjzZR/5/
这个 isPointInPoly 函数改编自这里https://github.com/substack/point-in-polygon,以及来自 fabricjs.com 的过滤器创建代码。
您的问题很有趣,在类似产品中也很有用。
var canvas = new fabric.Canvas('c1');
var src = "http://fiddle.jshell.net/img/logo.png";
canvas.backgroundColor = "#ccc";
canvas.renderAll();
var padding = 0;
fabric.Image.fromURL(src, function (img) {
img.set({
originX: 'left',
originY: 'top',
left: 120,
top: 20
});
var points = [{
x: 185,
y: 0
}, {
x: 250,
y: 100
}, {
x: 385,
y: 170
}, {
x: 0,
y: 245
}];
var polygon = new fabric.Polygon([{
x: 185,
y: 0
}, {
x: 250,
y: 100
}, {
x: 385,
y: 170
}, {
x: 0,
y: 245
}], {
left: 0,
top: 0,
originX: 'left',
originY: 'top',
fill: 'transparent',
stroke: 'black',
stokeWidth: 1
});
console.log(polygon.width + ":" + polygon.height);
canvas.add(img);
canvas.add(polygon);
polygon.selectable = false;
fabric.Image.filters.Redify = fabric.util.createClass({
type: 'Redify',
applyTo: function (canvasEl) {
var context = canvasEl.getContext('2d'),
imageData = context.getImageData(0, 0, canvasEl.width, canvasEl.height),
data = imageData.data;
var width = imageData.width;
var height = imageData.height;
width = Math.ceil (img.width);
height = Math.ceil (img.height);
console.log (width + ":" + height);
//console.log ("left=" + img.left + ":top=" + img.top);
for (var i = 0, len = data.length; i < len; i += 4) {
//data[i + 1] = 0;
//data[i + 2] = 0;
var x = Math.ceil(i / 4);
var y = Math.ceil(x / width);
x = x % width;
x = x * img.scaleX + img.left;
y = y * img.scaleY + img.top;
//console.log (x + ":" + y);
if (!isPointInPoly(points, {
x: x,
y: y
})) {
//alert (x + ":" + y);
//data[i + 1] = 0;
//data[i + 2] = 0;
data[i + 3] = 0;
}
}
context.putImageData(imageData, 0, 0);
}
});
fabric.Image.filters.Redify.fromObject = function (object) {
return new fabric.Image.filters.Redify(object);
};
img.filters.push(new fabric.Image.filters.Redify());
canvas.on("object:moving", function () {
img.applyFilters(canvas.renderAll.bind(canvas));
});
function isPointInPoly(vs, pt) {
var x = pt.x,
y = pt.y;
var inside = false;
for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) {
var xi = vs[i].x,
yi = vs[i].y;
var xj = vs[j].x,
yj = vs[j].y;
var intersect = ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if (intersect) inside = !inside;
}
return inside;
}
//polygon.selectable = false;
});