Trying to draw HTML and SVG to canvas to save thumbnails of various pieces of a dataviz app.
Currently failing because dataObjectUrl seems to taint HTML5 canvas.
<html xmlns="http://www.w3.org/1999/xhtml"> | |
<head> | |
<title>Canvas Drawing</title> | |
<meta charset="utf-8" /> | |
</head> | |
<style> | |
body, html { | |
margin: 0; | |
padding: 0; | |
} | |
.left { | |
position: fixed; | |
left:0; | |
top:0; | |
bottom:0; | |
right:50%; | |
background:rgb(188,188,188); | |
} | |
.right { | |
position: fixed; | |
right:0; | |
top:0; | |
bottom:0; | |
left:50%; | |
background:rgb(222,222,222); | |
} | |
</style> | |
<script> | |
function makeViz() { | |
_testDiv = d3.select(".left") | |
.append("div") | |
.attr("class", "target") | |
.style("font-size", "12px") | |
.style("background", "white") | |
.style("border", "1px solid black") | |
_testDiv.append("div") | |
.selectAll("p").data([0,0,0]).enter() | |
.append("p") | |
.style("border", function (d,i) {return i + "px dashed darkgray"}) | |
.html("Some kind of sample paragraphs with ") | |
.append("span") | |
.style("font-weight", function (d,i) {return i * 450}) | |
.html("spans.") | |
_testDiv.append("svg") | |
.attr("height", 200).attr("width", 300) | |
.selectAll("circle").data(d3.range(100)) | |
.enter() | |
.append("circle") | |
.style("fill", "blue") | |
.attr("r", 2) | |
.attr("cx", function() {return Math.random() * 200}) | |
.attr("cy", function() {return Math.random() * 300}) | |
var height = 0; | |
var width = 0; | |
d3.select(".right").append("canvas").attr("height", 200).attr("width", 200) | |
_fakeHTML = d3.select(".right").append("svg") | |
.attr("class", "rasterize") | |
.attr("height", 300).attr("width", 300) | |
.append("foreignObject") | |
.attr("id", "rasterizeFO") | |
.attr("height", "200px").attr("width", "200px") | |
var itm = d3.select("div.target").node(); | |
var cln = itm.cloneNode(true); | |
d3.select("#rasterizeFO").node().appendChild(cln); | |
DOMURL = window.URL || window.webkitURL || window; | |
var context = d3.select("canvas").node().getContext('2d'); | |
var img = new Image(); | |
var data = new XMLSerializer().serializeToString(d3.select("svg.rasterize").node()); | |
var svg = new Blob([data], {type: 'image/svg+xml;charset=utf-8'}); | |
var url = DOMURL.createObjectURL(svg); | |
img.onload = function () { | |
context.drawImage(img, 0, 0); | |
var dataURL = d3.select("canvas").node().toDataURL(); | |
d3.select(".right").data([0,0,0,0]) | |
.enter().append("img") | |
.attr("src", dataURL) | |
DOMURL.revokeObjectURL(url); | |
} | |
img.src = url; | |
} | |
</script> | |
<body onload="makeViz()"> | |
<div class="left"></div> | |
<div class="right"></div> | |
<footer> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script> | |
</footer> | |
</body> | |
</html> |
Is this helpful https://gist.github.com/biovisualize/8187844?