Skip to content

Instantly share code, notes, and snippets.

@gtb104
Last active October 10, 2015 14:07
Show Gist options
  • Save gtb104/3701528 to your computer and use it in GitHub Desktop.
Save gtb104/3701528 to your computer and use it in GitHub Desktop.

SVG vs HTML 5 Canvas Test

Comparing the performance of d3 when using SVG vs Canvas for rendering.

<!DOCTYPE html">
<!--
Canvas vs SVG Benchmark Tool
Copyright (c) 2009 Boris Smus, http://www.borismus.com
Licensed under the MIT license:
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
-->
<head>
<script type="text/javascript" src="http://d3js.org/d3.v2.js"></script>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.1.min.js'></script>
<style>
body {
margin: 0px auto;
width: 700px;
}
.filters .filter-container {
font-size: 12pt;
color: #3b3b3b;
float: left;
margin-right: 10px;
min-width: 100px;
}
div.title {
margin-bottom: 10px;
font-size: 16pt;
}
div.clear {
clear: both;
}
button {
width: 75px;
}
div.status {
position: relative;
left: 95px;
top: -23px;
font-size: 16pt;
color: #000;
}
div.status.error {
font-size: 20pt;
color: #f00;
}
div.chart {
margin-top: 10px;
background-color: rgba(128,128,128,0.5);
}
path {
stroke-width: 2;
fill: none;
}
path.SVG {
stroke: #4682b4;
}
path.HTML {
stroke: #f00;
}
circle {
stroke-width: 2px;
}
circle.SVG {
fill: #4682b4;
stroke: #386890;
}
circle.HTML {
fill: #f00;
stroke: #c00;
}
line {
stroke: #000;
stroke-width: 1px;
shape-rendering: crispEdges;
}
text {
fill: #000;
font-family: Arial;
font-size: 9pt;
}
text.datatip {
fint-size: 10pt;
}
text.title {
font-size: 18pt;
}
rect.datatip {
fill: #fff1a5;
}
</style>
</head>
<body>
<div class="filters">
<div class="filter-container">
<div class="title">Circle Count</div>
<input id="circleCount" value="100"/>
</div>
<div class="filter-container">
<div class="title">Circle Size</div>
<input id="circleSize" value="10"/>
</div>
<div class="filter-container">
<div class="title">Canvas Width</div>
<input id="canvasWidth" value="500"/>
</div>
<div class="filter-container">
<div class="title">Canvas Height</div>
<input id="canvasHeight" value="500"/>
</div>
<div class="filter-container">
<div class="title">Variation Count</div>
<input id="variationCount" value="10"/>
</div>
</div>
<div class="clear">
<button id="runButton" type="button" class="button">Go</button>
</div>
<div id="status" class="status"></div>
<div id="chart" class="chart"></div>
<div id="testRunner"></div>
<script type="text/javascript">
var _width = 700, _height = 400;
var parameters = {
circleCount: 100,
circleSize: 10,
canvasWidth: 500,
canvasHeight: 500
};
var paramNameHash = {
circleCount: 'Varying Number of Circles',
circleSize: 'Varying Circle Size',
canvasWidth: 'Varying Viewport Width',
canvasHeight: 'Varying Viewport Height'
};
var _variationCount = 10,
_results = {};
var CanvasElementTest = {
createGraphicsContext: function(canvasWidth, canvasHeight) {
var canvas = document.createElement('canvas');
canvas.width = canvasWidth;
canvas.height = canvasHeight;
canvas.style.width = canvasWidth + 'px';
canvas.style.height = canvasHeight + 'px';
this.context = canvas.getContext('2d');
this.width = canvasWidth;
this.height = canvasHeight;
return canvas;
},
drawCircle: function(x, y, radius) {
this.context.beginPath();
this.context.arc(x, y, radius, 0, Math.PI*2, true);
this.context.closePath();
this.context.fill();
},
clearAll: function() {
this.context.clearRect(0, 0, this.width, this.height);
}
};
var SVGTest = {
createGraphicsContext: function(canvasWidth, canvasHeight) {
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', canvasWidth);
svg.setAttribute('height', canvasHeight);
this.svg = svg;
return svg;
},
drawCircle: function(x, y, radius) {
var circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
if (isNaN(x)){
console.log("asdf");
}
circle.setAttribute('r', radius + 'px');
circle.setAttribute('cx', x + 'px');
circle.setAttribute('cy', y + 'px');
circle.setAttribute('style', 'fill: black;');
this.svg.appendChild(circle);
},
clearAll: function() {
var svg = this.svg;
for (var i = svg.childNodes.length - 1; i >= 0; i--)
{
svg.removeChild(svg.childNodes[i]);
}
}
};
var competingTechnologies = {
'SVG' : SVGTest,
'HTML': CanvasElementTest
};
var executionDuration = function( func ) {
var start = new Date();
func();
var end = new Date();
return end - start;
};
var runTest = function( technology, params ) {
benchmarkResults = {};
// Begin the test
benchmarkResults.creationTime = executionDuration(function() {
var graphicsElement = technology.createGraphicsContext(params.canvasWidth, params.canvasHeight);
$('#testRunner').append(graphicsElement);
});
benchmarkResults.totalDrawTime = 0;
var circlesPerRow = Math.max(parseInt((params.canvasWidth / params.circleSize) / 2, 10), 1);
var x, y;
// Draw circleCount circles of radius circleSize in rows.
for (var circleIndex = 0; circleIndex < params.circleCount; circleIndex++) {
// Compute the next (x, y) pair
var rowIndex = circleIndex % circlesPerRow;
x = rowIndex * params.circleSize * 2;
var colIndex = parseInt(circleIndex / circlesPerRow, 10);
y = colIndex * params.circleSize * 2;
var drawTime = executionDuration(function() {
technology.drawCircle(x, y, params.circleSize);
});
benchmarkResults.totalDrawTime += drawTime;
}
benchmarkResults.clearTime = executionDuration(function() {
technology.clearAll();
});
$('#testRunner').html('');
return benchmarkResults;
};
var getParams = function () {
var cc = $('#circleCount').val();
if (cc) parameters.circleCount = +cc;
var cs = $('#circleSize').val();
if (cs) parameters.circleSize = +cs;
var cw = $('#canvasWidth').val();
if (cw) parameters.canvasWidth = +cw;
var ch = $('#canvasHeight').val();
if (ch) parameters.canvasHeight = +ch;
var vc = $('#variationCount').val();
if (vc) _variationCount = +vc;
};
var updateStatus = function( m, error ) {
d3.select('#status')
.classed('error', function() { return (error) ? true : false; })
.html(m);
}
var startTestLoop = function() {
var result;
getParams();
result = performTest();
if (result) {
updateStatus('');
for (var item in parameters) {
buildChart(item);
}
}
else
{
updateStatus('There was an error running the test.', true);
}
$('#runButton').attr('disabled', null);
}
var onClick = function() {
$('#runButton').attr('disabled', 'disabled');
d3.selectAll('svg').remove();
updateStatus('Running Test...');
// This is retarded!
setTimeout(startTestLoop, 0);
};
var performTest = function () {
var compareAll = function( techs, parameters ) {
var result = {};
result.count = parameters[variedParam];
for (var techName in techs) {
var technology = techs[techName];
var benchmark = runTest(technology, parameters);
result[techName] = {};
result[techName].creationTime = benchmark.creationTime;
result[techName].totalDrawTime = benchmark.totalDrawTime;
result[techName].clearTime = benchmark.clearTime;
}
return result;
};
try {
// Vary parameters to test how the each competing technology does in
// relation to one another:
for (var variedParam in parameters) {
var originalValue = parameters[variedParam];
var count = _variationCount + 1;
var result = {};
_results[variedParam] = [];
for (var i = 1; i < count; i++) {
parameters[variedParam] = originalValue * i;
result = compareAll(competingTechnologies, parameters);
_results[variedParam].push(result);
}
// Reset the varied parameter to what it originally was
parameters[variedParam] = originalValue;
}
}
catch (error) {
_results = null;
}
console.log("Test Results:");
console.log(_results);
if (_results) return true;
};
var buildChart = function( param ) {
var data,
w = _width,
h = _height,
margin = 40;
y = d3.scale.linear().range([0 + margin, h - margin]),
x = d3.scale.linear().range([0 + margin, w - margin]),
minHeight = 0,
maxHeight = 0,
minWidth = 0,
maxWidth = 0;
var vis = d3.select("#chart").append("svg:svg")
.attr("width", w)
.attr("height", h);
// The title
vis.append('svg:text')
.text(paramNameHash[param])
.attr('class', 'title')
.attr('x', function(d) {
return w * 0.5 - this.offsetWidth * 0.5;
})
.attr('y', '1em');
var g = vis.append("svg:g")
.attr("transform", "translate(0, "+h+")");
// legend
g.append('svg:path')
.attr('class', 'SVG')
.attr('d', 'M50 -370 L60 -370 Z');
g.append('svg:text')
.text('SVG')
.attr("x", 65)
.attr("y", -365);
g.append('svg:path')
.attr('class', 'HTML')
.attr('d', 'M100 -370 L110 -370 Z');
g.append('svg:text')
.text('HTML Canvas')
.attr("x", 115)
.attr("y", -365);
function showTip(d, el) {
var _g = d3.select(el);
var _x = _g.select('circle').attr('cx')|0;
var _y = _g.select('circle').attr('cy')|0;
_g.append('svg:rect')
.attr('class', 'datatip')
.attr('width', '2em')
.attr('height', '1.1em')
.attr('x', _x + 5)
.attr('y', _y - 20);
_g.append('svg:text')
.attr('class', 'datatip')
.text(d)
.attr('x', _x + 10)
.attr('y', _y - 7);
}
function hideTip() {
d3.selectAll('.datatip').remove();
d3.selectAll('text.datatip').remove();
}
function draw() {
var lineSVG = d3.svg.line()
.x(function(d) { return x(d.count); })
.y(function(d) { return -1 * y(d.SVG.totalDrawTime); })
.interpolate('cardinal');
var lineHTML = d3.svg.line()
.x(function(d) { return x(d.count); })
.y(function(d) { return -1 * y(d.HTML.totalDrawTime); })
.interpolate('cardinal');
// The X axis
g.append("svg:line")
.attr("x1", x(minWidth))
.attr("y1", -1 * y(minHeight))
.attr("x2", x(maxWidth))
.attr("y2", -1 * y(minHeight));
// The Y axis
g.append('svg:line')
.attr("x1", x(minWidth))
.attr("y1", -1 * y(minHeight))
.attr("x2", x(minWidth))
.attr("y2", -1 * y(maxHeight));
// The X axis tick marks
g.selectAll(".xTicks")
.data(x.ticks(10))
.enter().append("svg:line")
.attr("class", "xTicks")
.attr("x1", function(d) { return x(d); })
.attr("y1", -1 * y(minHeight))
.attr("x2", function(d) { return x(d); })
.attr("y2", -1 * (y(minHeight) - 6));
// The Y axis tick marks
g.selectAll(".yTicks")
.data(y.ticks(10))
.enter().append("svg:line")
.attr("class", "yTicks")
.attr("y1", function(d) { return -1 * y(d); })
.attr("x1", x(minWidth) - 6)
.attr("y2", function(d) { return -1 * y(d); })
.attr("x2", x(minWidth));
// The X axis labels
g.selectAll(".xLabel")
.data(x.ticks(10))
.enter().append("svg:text")
.text(String)
.attr("x", function(d) { return x(d); })
.attr("y", -1*(margin*0.5))
.attr("text-anchor", "middle");
// The Y axis labels
g.selectAll(".yLabel")
.data(y.ticks(10))
.enter().append("svg:text")
.text(String)
.attr("x", 5)
.attr("y", function(d) { return -1 * y(d) });
// The actual lines
g.append("svg:path").attr("d", lineSVG(data))
.attr('class', 'SVG');
g.append("svg:path").attr("d", lineHTML(data))
.attr('class', 'HTML');
var showing = false;
// Add point circles
g.selectAll('.point')
.data(data)
.enter().append("svg:g")
.on('mouseover', function(d) {
if (!showing) {
showTip(d.SVG.totalDrawTime, this);
showing = true;
}
})
.on('mouseout', function() {
hideTip();
showing = false;
})
.append("svg:circle")
.attr("class", 'SVG')
.attr("cx", function(d) { return x(d.count); })
.attr("cy", function(d) { return -1 * y(d.SVG.totalDrawTime); })
.attr("r", 4);
g.selectAll('.point')
.data(data)
.enter().append("svg:g")
.on('mouseover', function(d) {
if (!showing) {
showTip(d.HTML.totalDrawTime, this);
showing = true;
}
})
.on('mouseout', function() {
hideTip();
showing = false;
})
.append("svg:circle")
.attr("class", 'HTML')
.attr("cx", function(d) { return x(d.count); })
.attr("cy", function(d) { return -1 * y(d.HTML.totalDrawTime); })
.attr("r", 4);
}
function prepData() {
data = _results[param];
// Update the data range
minSVG = d3.min(data, function(d){ return d.SVG.totalDrawTime; });
minHTML = d3.min(data, function(d){ return d.HTML.totalDrawTime; });
minHeight = 0;//Math.max(minSVG, minHTML);
maxSVG = d3.max(data, function(d){ return d.SVG.totalDrawTime; });
maxHTML = d3.max(data, function(d){ return d.HTML.totalDrawTime; });
maxHeight = Math.max(maxSVG, maxHTML);
y.domain([minHeight, maxHeight]);
minWidth = d3.min(data, function(d){ return d.count; });
maxWidth = d3.max(data, function(d){ return d.count; });
x.domain([minWidth,maxWidth]);
}
prepData();
draw();
};
$(document).ready(function() {
$('button').click(onClick);
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment