42
41

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

svg 要素を png 形式の画像に変換する

Last updated at Posted at 2014-12-10

はじめに

D3.js で作成した svg 要素を png 形式の画像に変換する方法.注意事項として,svg 要素の大きさ (width と height) が絶対値で指定されてないといけない(つまり 100% などでは駄目).また、テキスト要素にフォントを指定する必要がある.

フォントの指定の例

obj.attr("font-family", "sans-serif")
    .attr("font-size", "14px")
    .attr("fill", "black")

実際の変換

方針は,svg 要素の中身をデータ URI スキームで表し,canvas 要素に読み込ませる.

// #svg1: ターゲットの svg 要素
var width = $("#svg1").width()
var height = $("#svg1").height()
$("body").append("<canvas id='canvas1' class='hidden' width="
                                  + width + " height=" + height +"></canvas>")

var canvas = $("#canvas1")[0]
var ctx = canvas.getContext("2d")

var svg = $("#svg1")
svg.attr("viewBox", "0 0 " + width + " " + height)

var data = new XMLSerializer().serializeToString(svg[0])
var imgsrc = "data:image/svg+xml;charset=utf-8;base64,"
                       + btoa(unescape(encodeURIComponent(svgData)))
var image = new Image()
image.onload = function(){

    ctx.drawImage(image, 0, 0);
    // Optional: 自動でダウンロードさせる場合
    $("body").append("<a id='image-file' class='hidden' type='application/octet-stream' href='"
                       + canvas.toDataURL("image/png") + "' download='graph.png'>Donload Image</a>")
    $("#image-file")[0].click()

    // 後処理
    $("#canvas1").remove()
    $("#image-file").remove()

}
image.src = imgsrc;

(CoffeeScript版)

参考

42
41
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
42
41

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?