Skip to content

saveElement

Downloads an HTML or SVG element as a PNG, JPG, or SVG file.

Captures a DOM element and downloads it as png (default), jpg, or svg, named by filename plus the matching extension. Here the target is the white container, so the padding around the badge is part of the image. callback runs once the file has been handed to the browser; the status line shows it firing.

import {saveElement} from "@d3plus/export";
const container = document.querySelector("#badge");
saveElement(container, {type: "png", filename: "d3plus-demo", callback: () => console.log("saved")});
saveElement(container, {type: "jpg", filename: "d3plus-demo"}, {backgroundColor: "#ffffff"});
saveElement(container, {type: "svg", filename: "d3plus-demo"});

When the element passed is an <svg> and the type is svg, the markup is serialized directly instead of being wrapped in an HTML <foreignObject>, which is what vector editors such as Figma and Illustrator need to open the file. A chart’s own <svg> is viz.select().node() once it has rendered.

import {saveElement} from "@d3plus/export";
// The element is itself an <svg>, so it is serialized as-is.
saveElement(document.querySelector("#badge svg"), {type: "svg", filename: "d3plus-demo"});

Parameters

import {saveElement} from "@d3plus/export";
elemrequiredHTMLElement | SVGElement

The DOM element or d3 selection to export.

optionsSaveElementOptionsDefault {}

Additional options to specify.

renderOptionsSaveElementRenderOptionsDefault {}

Custom options to be passed to the html-to-image function.