gpt4 book ai didi

javascript - 在fabricjs Canvas 上实现ClipTo功能

转载 作者:行者123 更新时间:2023-12-03 07:45:44 25 4
gpt4 key购买 nike

如果我在 Canvas 最初加载时对 SVG 进行硬编码,我就可以将 Canvas 裁剪为某个形状。现在我尝试用点击功能来做到这一点。挑战在于,由于所有内容都已加载,当我单击它并加载剪切功能时,它会清除我的 Canvas ,只留下形状和背景。我正在寻找有关如何实现这一点的想法。我只知道如何在 new fabric.canvas 函数中加载 opts 。我怀疑我必须获取当前的 Canvas 数据,然后对其应用 opts 参数,但我不确定最好的方法。这是我的代码:

var canvas = new fabric.Canvas('imageCanvas');

$('#shape').on('click', function(){

var clipPath = new fabric.Path("M161.469,0.007 C161.469,0.007 214.694,96.481 214.694,96.481 C214.694,96.481 322.948,117.266 322.948,117.266 C322.948,117.266 247.591,197.675 247.591,197.675 C247.591,197.675 261.269,306.993 261.269,306.993 C261.269,306.993 161.469,260.209 161.469,260.209 C161.469,260.209 61.667,306.993 61.667,306.993 C61.667,306.993 75.346,197.675 75.346,197.675 C75.346,197.675 -0.010,117.266 -0.010,117.266 C-0.010,117.266 108.242,96.481 108.242,96.481 C108.242,96.481 161.469,0.007 161.469,0.007", ),

opts = {
controlsAboveOverlay: true,
backgroundColor: 'rgb(255,255,255)',
clipTo: function (ctx) {
if (typeof backgroundColor !== 'undefined') {
ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, 900, 900);
}
clipPath.render(ctx);
}
}
//obviously this is not going to work
var reloadShape = JSON.stringify(canvas);
canvas.loadFromJSON(reloadShape);
new fabric.Canvas('imageCanvas', opts);

});

最佳答案

您应该在应用程序中只初始化一次 Canvas ,否则您将丢失它的内容。

稍后,当您选择剪切路径时,创建并分配您的clipTo 函数。如果不需要任何其他处理,您也可以这样做

canvas.clipTo = clipPath._render;

无需创建新函数。

//do this once on your application:
var opts = {
controlsAboveOverlay: true,
backgroundColor: 'rgb(255,255,255)',
},
canvas = new fabric.Canvas('imageCanvas', opts);

$('#shape').on('click', function(){

var clipPath = new fabric.Path("M161.469,0.007 C161.469,0.007 214.694,96.481 214.694,96.481 C214.694,96.481 322.948,117.266 322.948,117.266 C322.948,117.266 247.591,197.675 247.591,197.675 C247.591,197.675 261.269,306.993 261.269,306.993 C261.269,306.993 161.469,260.209 161.469,260.209 C161.469,260.209 61.667,306.993 61.667,306.993 C61.667,306.993 75.346,197.675 75.346,197.675 C75.346,197.675 -0.010,117.266 -0.010,117.266 C-0.010,117.266 108.242,96.481 108.242,96.481 C108.242,96.481 161.469,0.007 161.469,0.007", );

canvas.clipTo = function (ctx) {
if (typeof backgroundColor !== 'undefined') {
ctx.fillStyle = backgroundColor;
ctx.fillRect(0, 0, 900, 900);

//for clipping _render would be enough.
// but .render() will allow you to position the path where you want with top and left
clipPath.render(ctx);
}
// display new canvas clipped.
canvas.renderAll();

});

关于javascript - 在fabricjs Canvas 上实现ClipTo功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35217031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com