D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
nicksrandall
Full window
Github gist
SVG to Canvas Test
<!DOCTYPE html> <html> <head> <script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script> </head> <body> <canvas id="canvas" style="border:2px solid black;" width="960" height="500"></canvas> <script> var size = 1000; var height = 500; var width = 960; var charge = -0.3; var data = d3.range(size).map(function(){ return {r: Math.floor(Math.random() * 8 + 2)}; }); var start = new Date(); var time = 0; var ticks = 0; var force = d3.layout.force() .size([width, height]) .nodes(data) .charge(function(d){ return d.r * d.r * charge; }) .start(); var nodes = force.nodes(); var svg = d3.select(document.createElementNS("https://www.w3.org/2000/svg","svg")) .attr({ height: height, width: width }); var circles = svg.selectAll('circle') .data(nodes) .enter() .append('circle') .attr('r', function(d){ return d.r; }) .style({ fill: 'steelblue' }); force.on('tick', function(){ var renderStart = new Date(); circles.attr({ cx: function(d){ return d.x; }, cy: function(d){ return d.y; } }); time += (new Date() - renderStart); ticks++; }); force.on('end', function(){ var totalTime = new Date() - start; console.log('Total Time:', totalTime); console.log('Render Time:', time); console.log('Ticks:', ticks); console.log('Average Time:', totalTime / ticks); }); var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var DOMURL = window.URL || window.webkitURL || window; var img = new Image(); renderToCanvas(); function renderToCanvas () { var data = svg.node().outerHTML.replace('<svg', '<svg xmlns="https://www.w3.org/2000/svg"'); console.log(data); ctx.clearRect(0, 0, canvas.width, canvas.height); var svgImg = new Blob([data], {type: 'image/svg+xml;charset=utf-8'}); var url = DOMURL.createObjectURL(svgImg); img.onload = function () { ctx.drawImage(img, 0, 0); DOMURL.revokeObjectURL(url); } img.src = url; } </script> </html>
Modified
http://d3js.org/d3.v3.min.js
to a secure url
https://d3js.org/d3.v3.min.js