简体   繁体   English

使用 Fabric.js 访问 SVG 属性

[英]Access SVG attributes using Fabric.js

I'd like to load a SVG image into canvas using Fabric.js and have access to all attributes of it.我想使用 Fabric.js 将 SVG 图像加载到画布中,并可以访问它的所有属性。

Let's assume I have an image like this: SVG Image假设我有一个这样的图像: SVG Image

I tried to it using Fabric.js on 3 ways: 1. (Saved as String) - this method is not loading my image, I took other SVG and attributes can be accessed with svgImg.fill.color property.我尝试通过 3 种方式使用 Fabric.js: 1.(另存为字符串)-此方法不加载我的图像,我使用了其他 SVG 并且可以使用 svgImg.fill.color 属性访问属性。

fabric.loadSVGFromString(svg, function (objects, options) {
        var svgImg = fabric.util.groupSVGElements(objects, options);
        canvas.add(svgImg);
    });

2. Directly from URL: 2.直接从网址:

fabric.loadSVGFromURL(URLsvg, function (objects, options) {
        var svgImg = fabric.util.groupSVGElements(objects, options);
        canvas.add(svgImg);
    });

3.Using fabric.Image: 3.使用fabric.Image:

<img id="Test_Img" src="~/SVG/homer-simpson.svg" style="display: none;"  />


var Img = document.getElementById('Test_Img');
    var imgInstance = new fabric.Image(Img, {
        left: 90,
        top: 80
    });

How can I access inner attributes of my SVG and change for example color of Homers T-Shirt?如何访问我的 SVG 的内部属性并更改例如 Homers T 恤的颜色?

Loaded SVG objects become groups in fabric.js (if they are not simple geometric forms like a rectangle, circle, etc.).加载的 SVG 对象成为 fabric.js 中的组(如果它们不是简单的几何形式,如矩形、圆形等)。

You can access the members of the group with getObjects(), which returns an array.您可以使用 getObjects() 访问组的成员,它返回一个数组。

Here is a simple example.这是一个简单的例子。 It reads an SVG consisting of 3 arcs and changes the color of the first arc to blue:它读取由 3 个弧组成的 SVG 并将第一个弧的颜色更改为蓝色:

var canvas = new fabric.Canvas('canvas', { preserveObjectStacking: true });
canvas.backgroundColor="#fff";
canvas.renderAll();

fabric.loadSVGFromURL("https://media-public.canva.com/MABtmZU4zXQ/1/screen.svg",function(objects,options) {

    var loadedObjects = fabric.util.groupSVGElements(objects, options);

    loadedObjects.set({
            width: 300,
            height: 150
    });

    canvas.add(loadedObjects);

    // Change the first arc to blue
    loadedObjects.getObjects()[0].set({fill: "blue"});

    canvas.renderAll();

});

It runs with fabric.js Version 3.5.它与 fabric.js 版本 3.5 一起运行。 Working example: https://jsfiddle.net/awehring/k7azLb84/9/工作示例: https : //jsfiddle.net/awehring/k7azLb84/9/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM