Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@biovisualize
Last active February 21, 2023 21:08
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save biovisualize/5400576 to your computer and use it in GitHub Desktop.
Save biovisualize/5400576 to your computer and use it in GitHub Desktop.
Fast pixel drawing on canvas
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
<style type="text/css">
</style>
</head>
<body>
<script type="text/javascript">
// Following this idea: https://hacks.mozilla.org/2011/12/faster-canvas-pixel-manipulation-with-typed-arrays/
var chartSize = 1000;
var dataSize = 1000;
var dataset = d3.range(dataSize).map(function(d, i){return d3.range(dataSize).map(function(d, i){return ~~(Math.random()*255);});});
var canvas = d3.select('body')
.append('canvas')
.style({position: 'absolute', width: chartSize + 'px', height: chartSize + 'px'})
.attr({width: dataSize, height: dataSize})
.node();
var canvasWidth = canvas.width;
var canvasHeight = canvas.height;
var ctx = canvas.getContext('2d');
var imageData = ctx.getImageData(0, 0, canvasWidth, canvasHeight);
var buf = new ArrayBuffer(imageData.data.length);
var buf8 = new Uint8ClampedArray(buf);
var data = new Uint32Array(buf);
for (var y = 0; y < canvasHeight; ++y) {
for (var x = 0; x < canvasWidth; ++x) {
var value = dataset[y][x];
data[y * canvasWidth + x] =
(255 << 24) | // alpha
(value/2 << 16) | // blue
(value << 8) | // green
255; // red
}
}
imageData.data.set(buf8);
ctx.putImageData(imageData, 0, 0);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment