svg -> canvas -> img -> a href
<div id="chart1" style="height:400px;"></div>
<a id="image_download"></a>
function btn_image(){
var svg = $("#chart1 svg")[0];
var svgData = new XMLSerializer().serializeToString(svg);
var canvas = document.createElement("canvas");
var svgSize = svg.getBoundingClientRect();
canvas.width = svgSize.width;
canvas.height = svgSize.height;
var ctx = canvas.getContext("2d");
var img = document.createElement("img");
img.setAttribute("src", "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(svgData))));
img.onload = function() {
ctx.drawImage(img, 0, 0);
var obj = document.getElementById("image_download");
obj.href = canvas.toDataURL("image/png");
obj.download = 'download.png';
$("#image_download")[0].click();
};
}
//
0. chart1에 chart가 그려졌다는 가정하에
1. page가 UTF-8이라서 unescape(encodeURIComponent 를 추가했다.
'웹 > javascript' 카테고리의 다른 글
typeof, instanceof (0) | 2018.05.20 |
---|---|
setTimeout 과 this (0) | 2018.05.19 |
css (0) | 2018.05.02 |
Browsersync, VSCode, Brackets (0) | 2018.05.01 |
텍스트 자동 변환1 (0) | 2016.10.02 |