【发布时间】:2016-07-22 17:08:39
【问题描述】:
我正在使用Fabricjs 创建一个应用程序。
每次Minicolors 输入更改时,我都必须将 SVG 文件添加到画布并更改颜色。
我首先让浏览器将 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');
});
然后,当它们被点击时,我将 DOM 中的 SVG 图像加载到画布中,如下所示:
$('#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();
});
});
现在我的下一个目标是如何更改所选 svg 文件的路径颜色? 我的主要猜测是遵循以下步骤:
- 保存所选 SVG 的左侧和顶部位置
- 在 DOM 中更改 SVG 图像的颜色
- 移除选定的 SVG 对象
- 在保存的左侧和顶部位置使用新颜色将其替换为新 SVG
但我想:“所以每次 Minicolors 输入发生变化时我都必须执行所有这些操作?以后不会是性能问题吗?”
还有比这更好的方法吗?这是一个JSFiddle,可以帮助您入门。谢谢。
【问题讨论】:
标签: javascript svg fabricjs