Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart draw id from SVG file on canvas

Tags:

canvas

svg

dart

I'd like to load an svg, extract a group by the id, and draw it to a canvas.

If the file was an image I would do:

_image = new html.ImageElement()
        ..src = src;
_canvas.context2D.drawImageScaledFromSource(_image, ox, oy, ow, oh, x, y, w, h)

I'd like to do the same thing but with an svg file, and I'd like to pick and choose which id from the svg file to draw. With multiple ids draw to different parts of the canvas.

Now I have:

var groupToDraw;
HttpRequest.getString("img.svg").then((text) {
    svg.SvgElement pimage = new svg.SvgElement(text);
    groupToDraw = pimage.querySelector("#ID");
}

But I'm not sure how to draw just this element on the screen. Also some of the groups reference patterns in other parts of the file, although I could skip them for now.

If it helps to do this in pyQt I did:

renderer = QSvgRenderer(path)
pix = QtGui.QPixmap(width, height)
pix.fill(Qt.transparent)
painter = QtGui.QPainter(pix)
renderer.render(painter, id)
like image 530
Peter Hofmann Avatar asked Jan 25 '26 02:01

Peter Hofmann


1 Answers

If you load some svg text from file and create an SvgElement from that string, you will be able to see the ID on the element:

var fileID;
HttpRequest.getString('file.svg').then((text) {
  svg.SvgElement temp = new svg.SvgElement.svg(text);
  fileID = temp.id;
});  

You can then create a group element by querying the group's id, surround the GElement with SVG tags in a string, create a blob from that string and a URL from that blob, then create an ImageElement from the URL and draw the image on the canvas:

svg.GElement g = temp.querySelector("#id2");

var str = '<svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="32px"   
  height="32px" viewBox="0 0 32 32">${g.innerHtml}</svg>';

var blob = new Blob([str], "image/svg+xml;charset=utf-8");
var url = Url.createObjectUrlFromBlob(blob);

img = new ImageElement(src: url)
    ..onLoad.listen((Event e) { ctx.drawImage(img, 0, 0); });
like image 82
ringstaff Avatar answered Jan 28 '26 03:01

ringstaff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!