Nic*_*eau 5 javascript svg fabricjs
我正在使用Fabricjs创建一个应用程序。我必须向画布添加一个 SVG 文件,并在每次Minicolors
输入发生变化
时更改颜色。
我首先让浏览器将 SVG 图像显示为 SVG 代码,如下所示:
$('img[src$=".svg"]').each(function(){
var $img = $(this),
imgURL = $img.attr('src'),
attributes = $img.prop('attributes');
$.get(imgURL, function(data) {
// Get the SVG tag, ignore the rest
var $svg = $(data).find('svg');
// Remove any invalid XML tags as per http://validator.w3.org
$svg = $svg.removeAttr('xmlns:a');
// Make sure that every attribute was copied
$.each(attributes, function() {
$svg.attr(this.name, this.value);
});
// Replace image with new SVG
$img.replaceWith($svg);
}, 'xml');
});
Run Code Online (Sandbox Code Playgroud)
然后,当单击 SVG 图像时,我将它们从 DOM 加载到画布上,如下所示:
$('#images').on('click', 'svg', function() {
var serializer = new XMLSerializer(),
svgStr = serializer.serializeToString(this);
fabric.loadSVGFromString(svgStr,function(objects, options) {
options.id = this.id;
var obj = fabric.util.groupSVGElements(objects, options);
canvas.add(obj);
obj.scaleToHeight(127) // Scales it down to some small size
.scaleToWidth(90)
.center() // Centers it (no s**t, Sherlock)
.setCoords();
canvas.setActiveObject(obj).renderAll();
});
});
Run Code Online (Sandbox Code Playgroud)
现在,我的下一个目标是如何更改所选 svg 文件的路径颜色?我的主要猜测是遵循以下步骤:
但我想:“那么每次 Minicolors 输入发生变化时我都必须执行所有这些操作?以后这不会成为性能问题吗?”
还有比这更好的方法吗?这是一个可以帮助您入门的JSFiddle 。谢谢。
Nick Rameau的回答不适用于最新版本的 Fabricjs。
就我而言,我正在与fabricjs 3.5.
在最新版本的fabricjs中,该paths属性已被删除。数据paths已添加到_objects属性中。
这就是我让它为我工作的方式。
var obj = this.canvas.itemObj;
var color = '#ff00ff';
if (obj && obj._objects) {
for (var i = 0; i < obj._objects.length; i++) {
obj._objects[i].set({
fill: color
});
}
}
Run Code Online (Sandbox Code Playgroud)
当添加到画布时,SVG 对象包含一个名为“paths”的属性,其中包含构建图像的所有路径。所以我们这样做:
activeObject.paths.forEach(function(path) {path.fill = color});
Run Code Online (Sandbox Code Playgroud)
但我想知道对于巨大的 SVG 文件来说这是否不会成为性能问题(希望我不会达到这一点)。这是一个正在运行的JSFiddle。