当画布最初加载时,如果我硬编码SVG,我就能够将画布剪裁成一个形状。现在,我尝试使用一个单击函数来完成这个任务。挑战在于,由于所有东西都已加载,当我单击它并加载剪辑功能时,它会清除我的画布,只留下形状和背景。我正在寻找如何实现这一目标的想法。我只知道如何在opts函数中加载new fabric.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);
});发布于 2016-02-05 05:59:58
您应该在应用程序中初始化画布一次,否则会丢失它的内容。
稍后,当您选择裁剪路径时,创建并分配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();
});https://stackoverflow.com/questions/35217031
复制相似问题