flixe
flixe

Reputation: 656

Convert svg to png using Canvg: "target.childnodes is undefined" error

I have an SVG graphic which I want to convert to PNG and then offer it as a download. If I select the SVG and create the canvas element with jQuery I constantly get the error in the title. If I use basic javascript functions like createElement and getElementById it somehow seems to work.

So what does this error mean? If I take a look at the canvg source code, target seems to be the canvas in the canvg method (see code below). But of course it does not have any children, I did not append anything else to it.

Here is my code:

var svg = $('#chart')[0],
canvas = $("canvas"),
serializer = new XMLSerializer(),
svgString = serializer.serializeToString(svg);

canvas.width  = svg.width;
canvas.height = svg.height;

canvg(canvas, svgString);

Upvotes: 1

Views: 401

Answers (1)

Kaiido
Kaiido

Reputation: 136986

You can't pass a jQuery object to canvg, you have to pass an element.

What it seems to me is that canvg does check itself if you did pass a container so it has to retrieve the canvas element.
Actually they don't even do this... I don't know what they are looking into the childNodes, but they do. (if you pass an other HTMLElement, it will throw a target.getContext is not a function error...)

As any other HTML elements, CanvasElement does implement the childNodes property, so they certainly check for target.childNodes.length, if truthy, check for a canvas element into the list, else use the canvas. This single call, if they don't check for (target.childNodes && target.childNodes.length) will throw the error you got.


So the easy fix for you is just to set canvas = $("canvas")[0].

Upvotes: 1

Related Questions