我有一个Fabric.js画布,允许根据对象占用的区域进行动态剪裁。然而,剪切区域对SVG /形状的处理方式与图像不同,使得它们略微偏移并且突破了#34;裁剪区。要重新创建:
如何纠正?非常感谢任何帮助,谢谢!
裁剪功能代码:
var clipByName = function (ctx) {
this.setCoords();
var clipObj = findByClipName(this.clipName);
var scaleXTo1 = (1 / this.scaleX);
var scaleYTo1 = (1 / this.scaleY);
ctx.save();
var ctxLeft = -( this.width / 2 ) + clipObj.strokeWidth;
var ctxTop = -( this.height / 2 ) + clipObj.strokeWidth;
var ctxWidth = clipObj.width - clipObj.strokeWidth;
var ctxHeight = clipObj.height - clipObj.strokeWidth;
ctx.translate( ctxLeft, ctxTop );
ctx.scale(scaleXTo1, scaleYTo1);
ctx.rotate(degToRad(this.angle * -1));
ctx.beginPath();
var isPolygon = clipObj instanceof fabric.Polygon;
// polygon cliping area
if(isPolygon)
{
// prepare points of polygon
var points = [];
for(i in clipObj.points)
points.push({
x: (clipObj.left + clipObj.width / 2) + clipObj.points[i].x - this.oCoords.tl.x,
y: (clipObj.top + clipObj.height / 2) + clipObj.points[i].y - this.oCoords.tl.y
});
ctx.moveTo(points[0].x, points[0].y);
for(i=1; i<points.length; ++i)
{
ctx.lineTo(points[i].x, points[i].y);
}
ctx.lineTo(points[0].x, points[0].y);
}
// rectangle cliping area
else
{
ctx.rect(
clipObj.left - this.oCoords.tl.x,
clipObj.top - this.oCoords.tl.y,
clipObj.width,
clipObj.height
);
}
ctx.closePath();
ctx.restore();
}
答案 0 :(得分:4)
您应该指定在缩放路径时发生这种情况。 偏移来自于在计算ctxLeft和ctxTop时使用strokeWidth。
这是一个更简单的clipByName函数,它不需要做很多数学来绘制剪切区域,也不需要调用.setCoords()
并使用.oCoords
https://jsfiddle.net/hncqbhah/2/
var clipByName = function (ctx) {
var clipObj = findByClipName(this.clipName);
ctx.save();
ctx.setTransform(1,0,0,1,0,0);
ctx.beginPath();
var isPolygon = clipObj instanceof fabric.Polygon;
// polygon cliping area
if(isPolygon)
{
// prepare points of polygon
var points = [];
for(i in clipObj.points)
points.push({
x: (clipObj.left + clipObj.width / 2) + clipObj.points[i].x ,
y: (clipObj.top + clipObj.height / 2) + clipObj.points[i].y
});
ctx.moveTo(points[0].x, points[0].y);
for(i=1; i<points.length; ++i)
{
ctx.lineTo(points[i].x, points[i].y);
}
ctx.lineTo(points[0].x, points[0].y);
}
// rectangle cliping area
else
{
ctx.rect(
clipObj.left,
clipObj.top,
clipObj.width,
clipObj.height
);
}
ctx.closePath();
ctx.restore();
}
同样要绑定clipTo函数,不需要io loDash:
obj.set({
clipName: 'clip2',
clipTo: clipByName
}
这就够了。