gpt4 book ai didi

javascript - 如何在 Canvas 上更改 svg 颜色 - Fabricjs

转载 作者:行者123 更新时间:2023-11-30 00:11:19 43 4
gpt4 key购买 nike

我正在使用 Fabricjs 创建一个应用程序.
我必须在 Canvas 上添加一个 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');
});

然后我在单击时将 SVG 图像从 DOM 加载到 Canvas ,如下所示:

$('#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 文件的路径颜色?我的主要猜测是遵循以下步骤:

  1. 保存所选 SVG 的左侧和顶部位置
  2. 更改 DOM 中 SVG 图像的颜色
  3. 删除选定的 SVG 对象
  4. 在保存的左侧和顶部位置使用新颜色将其替换为新的 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
});
}
}

关于javascript - 如何在 Canvas 上更改 svg 颜色 - Fabricjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36380963/

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