javascript - 服务器端 d3 - 将 SVG 编码为 Base64 图像

标签 javascript node.js d3.js svg

我正在尝试将 D3 图表编码为 Base64 图像以在 HTML 电子邮件中使用

到目前为止我已经:

var express = require('express');
var app = express();
var jsdom = require('jsdom');

app.get('/chart', function (request, response) {
    try {
        jsdom.env(
            "<html><body><svg id=\"svg\"></svg></body></html>",
            ['http://d3js.org/d3.v3.min.js'],
            function (err, window) {
                var svg = window.d3.select("svg")
                    .attr("width", 100)
                    .attr("height", 100);

                svg.append("rect")
                    .attr("x", 10)
                    .attr("y", 10)
                    .attr("width", 80)
                    .attr("height", 80)
                    .style("fill", "orange");

                var encoded = ...; // How do I now encode this?

                response.send({
                    "html": window.d3.select("body").html(),
                    "encoded": encoded
                });
            }
        );
    } catch (err) {
        console.error(err);
    }
});

// Run Server
var port = process.env.PORT || 8305;
var server = app.listen(port, function () {
    var host = server.address().address;
    console.log('App listening at http://%s:%s', host, port);
});

这会输出有用的 SVG html,但是我还想要第二个响应字段编码,其中应包含如下内容,我可以在 HTML 电子邮件中使用:

"encoded": "data:image/png;base64,iVBORw0KGgoAAAANSUhEU...etc"

如何编码此 SVG?我希望尽可能避免任何文件写入,并直接从 SVG 转换为编码图像。另外,我知道您可以在电子邮件中使用 SVG,但我更希望它采用编码图像格式。谢谢!

最佳答案

设置 "xmlns"根属性<svg> Node 到"http://www.w3.org/2000/svg"<svg> document 内的 Node 或与 .attr() .

data URI 方案包括

data:[<media type>][;base64],<data>

因为我们知道 <media type>将是image/svg+xml我们想要 base64结果数据的表示,我们可以定义一个变量,我们将连接到 base64 <svg> 的表示.

let data = "data:image/svg+xml;base64,";

然后我们得到.outerHTML<svg>元素

// optionally preceded by `XML` declaration `<?xml version="1.0" standalone="yes"?>`
let svgString = svg[0][0].outerHTML; 

调用 btoa() svgString作为参数

The btoa(data) method must throw an "InvalidCharacterError" DOMException if data contains any character whose code point is greater than U+00FF. Otherwise, the user agent must convert data to a sequence of octets whose nth octet is the eight-bit representation of the code point of the n th character of data, and then must apply the base64 algorithm to that sequence of octets, and return the result. [RFC4648]

let base64 = window.btoa(svgString);
// concatenate `data` and `base64`
let dataURI = data + base64;

response.send({
                "html": window.d3.select("body").html(),
                "encoded": dataURI
             });

let svg = window.d3.select("svg")
  .attr("xmlns", "http://www.w3.org/2000/svg")
  .attr("width", 100)
  .attr("height", 100);

svg.append("rect")
  .attr("x", 10)
  .attr("y", 10)
  .attr("width", 80)
  .attr("height", 80)
  .style("fill", "orange");

let data = "data:image/svg+xml;base64,";
let svgString = svg[0][0].outerHTML;
let base64 = window.btoa(svgString);
let dataURI = data + base64;

console.log(dataURI);

document.querySelector("iframe").src = dataURI;
<script src="https://d3js.org/d3.v3.min.js"></script>
<svg></svg>
<iframe></iframe>

关于javascript - 服务器端 d3 - 将 SVG 编码为 Base64 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43293795/

相关文章:

Javascript 无法与 jQuery UI 一起使用

javascript - C3.js x 轴显示所有其他类别

javascript - typescript 和 d3 版本 v3 中的可折叠树

node.js - 用动态 url 包裹标题

android - 当我尝试上传新的时,我的 firebase 功能被删除了

node.js - Windows 上多 Node 和 Fugue 的替代方案?

javascript - dc.js 错误 : d3. 时间未定义

php - 在同一页面上的 php 和 javascript 之间共享数据

javascript - jquery - 无法使元素淡出/淡入

javascript - 为什么我的网站可以使用 Safari,而不是 FireFox 或 IE?