D3.jsで描画したチャートをダウンロードできるようにするモジュール。 cssで適用したカラーなども反映されるようになっている。
未完成。
サーバー側でレンタリングする方が楽かも。
ちょっと後悔している。
以下、勘違いして書いているかもしれないので要注意。
a要素のDownload属性が使えないので、ダウンロードされずブラウザ上でファイルが開いてしまう。なんかいい方法があったら教えてください。
image要素のsrcにデータURIスキームとしてsvgを読み込ませるにはbase64にエンコードする必要がある。window.btoaはユニコードに対応していないので、svgに日本語が含まれている場合は別途base64エンコード処理を実装する必要がある。めんどい 頑張ってbase64に変換してimgタグに読みこませても、canvasのdrawImageに渡すとセキュリティエラーがでる。
(今回はcanvgを使って上記問題を回避した。でもあんまり綺麗では無い)
その他、img.onloadの発火がsvgの読み込みが終わる前に発火してたり、そもそも発火しなかったりするので訳がわからないよ。
Built with blockbuilder.org
xxxxxxxxxx
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title></title>
<style>
html, body {
width: 100%;
height: 100%;
padding: 0px;
margin: 0px;
}
#chart {
width: 900px;
height: 450px;
}
.vbarChart .bar {
fill:blue;
}
/* axis */
.vbarChart .axis {
}
.vbarChart .axis .domain {
stroke: #333333;
}
.vbarChart .tick line {
stroke: #333333;
stroke-width: 1px;
}
.vbarChart .tick text {
fill: #333333;
font-size: 14px;
letter-spacing: .05em;
}
/* grid */
.vbarChart .grid line {
stroke: #cccccc;
stroke-dasharray: 3,3;
}
/* label */
.vbarChart .label {
font-size: 12px;
font-weight: normal;
letter-spacing: .05em;
}
</style>
</head>
<body>
<div id="chart"></div>
<button id="downloadSVG">download SVG</button>
<button id="downloadPNG">download PNG</button>
<script src="https://gabelerner.github.io/canvg/canvg.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/4.1.1/d3.min.js"></script>
<script src="barchart.js"></script>
<script src="downloader.js"></script>
<script>
!(function(){
"use strict"
//ランダムデータセット
var data = ["アメリカ", "日本", "フランス", "イギリス", "スイス"].map(function(d){
var r = ~~(Math.random() * 100)
if (Math.random() > 0.2){
var cos = Math.sin(r * Math.PI / 180)
}else{
var cos = -Math.sin(r * Math.PI / 180)
}
var value = cos*100
return {"国名":d, "値":value}
})
//barChartモジュール初期設定
var BarChart = createVBarChart()
.margin({top:40, left:100, bottom:40, right:100})
.x(function(d){ return d["国名"] })
.y(function(d){ return d["値"] })
.xAxisLabel("国名")
.xAxisLabelOption({y:"-0.5em"})
.yAxisGridVisible(true)
.yAxisLabel("値")
.yAxisLabelOption({y:"-0.5em", "text-anchor":"middle"})
//downloaderモジュールのインスタンス生成
var downloader = createDownloader()
//セレクターにbarChartモジュールとdownloaderモジュールを適用
var selector = d3.selectAll("#chart")
.datum(data)
.call(BarChart)
.call(downloader)
d3.select("#downloadSVG").on("click", selector.downloadSVG )
d3.select("#downloadPNG").on("click", selector.downloadPNG )
}())
</script>
</body>
</html>
Modified http://gabelerner.github.io/canvg/canvg.js to a secure url
https://gabelerner.github.io/canvg/canvg.js
https://cdnjs.cloudflare.com/ajax/libs/d3/4.1.1/d3.min.js