在Node中以.svg扩展名预渲染svg

时间:2019-03-09 17:19:40

标签: javascript node.js d3.js svg jsdom

我想在服务器上预渲染d3图形,并让它在运行localhost:3000 / circle.svg时仅提供svg代码,因此在另一个文件中,我可以拥有<img src="http://localhost:3000/circle.svg />

这是我到目前为止的代码。我可以预渲染圆圈,但是我没有一个可以指向的svg扩展文件,该文件仅包含<svg>代码。相反,它具有整个dom。但是我正在使用JSDOM,所以也许这不是开始的正确方法。有什么想法吗?

const {send} = require('micro');

const d3 = require('d3');
const jsdom = require('jsdom');
const { JSDOM } = jsdom; 

module.exports = function(request, response) {
    const { window } = new JSDOM(`<script src="https://d3js.org/d3.v5.min.js"></script><svg id="dataviz-container"></svg>`, { runScripts: "dangerously", resources: "usable", pretendToBeVisual: true }); 

var el = window.document.querySelector('#dataviz-container')
var body = window.document.querySelector('body')
var circleId = 'a2324'  // say, this value was dynamically retrieved from some database

var clientScript = "d3.select('#" + circleId + "').transition().delay(1000).attr('fill', '#f9af26')"

    d3.select(el)
            .attr('width', 600)
            .attr('height', 300)
            .append('circle')
                .attr('cx', 300)
                .attr('cy', 150)
                .attr('r', 30)
                .attr('fill', '#26963c')
                .attr('id', circleId) // say, this value was dynamically retrieved from some database

    d3.select(body)
        .append('script')
        .html(clientScript)

    // save result in an html file, we could also keep it in memory, or export the interesting fragment into a database for later use
    var svgsrc = window.document.documentElement.innerHTML

    send(response, 200, svgsrc);
}

0 个答案:

没有答案