我使用此代码片段将笔划添加到图像中
fabric.Image.fromURL('https://mediatours.ca/img/placeholder.jpg', function(img) {
img.scale(0.2).set({
left: 10,
top: 150,
angle: 0,
stroke: "#FF0000",
strokeWidth: 10
});
canvas.add(img);
});
然后创建一个织物矩形来剪切图像
var rect = new fabric.Rect({
left: 10,
top: 20,
rx: 5
ry: 5,
width: 100
height: 100,
fill: 'transparent',
absolutePositioned: true,
originX: 'center',
originY: 'center',
stroke: '#000000',
strokeWidth: 100,
});
然后将 ClipPath 属性设置为 rect
img?.set('clipPath', rect);
这会产生这样的输出(https://i.sstatic.net/f5iZhKr6.png)
问题是我如何确保图像也获得类似于画布的圆形边框
使用单圆角和描边矩形不会给您带来太多影响,就像使用 Fabric.js 一样,实际描边总是会扩展到矩形的外部。 所以像这样:
var rect = new fabric.Rect({
width: 200,
height: 100,
stroke: "black",
fill: "transparent",
strokeWidth: 20,
rx:10,
ry:10
});
看起来像:
这个技巧很简单。您需要使用两个矩形,而不是仅使用前面提到的单个矩形:
let canvas = new fabric.Canvas("c");
fabric.Image.fromURL("https://mediatours.ca/img/placeholder.jpg", function(img) {
let strokeWidth = 100;
let rect = new fabric.Rect({
left: -strokeWidth / 2,
top: -strokeWidth / 2,
rx: 50,
ry: 50,
width: img.width,
height: img.height,
fill: "#000000",
stroke: "#000000",
strokeWidth: strokeWidth
});
img.set("clipPath", new fabric.Rect({
left: -img.width / 2,
top: -img.height / 2,
rx: 50,
ry: 50,
width: img.width,
height: img.height,
fill: "transparent"
}));
let group = new fabric.Group([rect, img]);
group.scale(0.25).set({
left: 10,
top: 150,
angle: 0
});
canvas.add(group);
canvas.centerObject(group);
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/fabric.min.js"></script>
<canvas id="c" width="400" height="300" style="border:1px solid #ccc">