Skip to content

Instantly share code, notes, and snippets.

@rhengles rhengles/index.html
Created Aug 24, 2017

Embed
What would you like to do?
Canvas Rainbow
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Canvas Rainbow</title>
</head>
<body>
<canvas></canvas>
<script src="index.js"></script>
</body>
</html>
// https://jsfiddle.net/qw549Luf/
var w = 256 * 6;
var h = 256 * 2;
var pixels = w * h;
var r = [ 1, 1, 0, 0, 0, 1];
var g = [ 0, 1, 1, 1, 0, 0];
var b = [ 0, 0, 0, 1, 1, 1];
var one256 = 1 / 256;
var cv = document.querySelector('canvas');
cv.width = w;
cv.height = h;
var ct = cv.getContext('2d');
var img = ct.createImageData(w,h);
var sectsize = 256 * 4;
var rowsize = sectsize * 6;
for ( var row = 0; row < h; row++ ) {
var rowpos = row * rowsize;
for ( var sect = 0; sect < 6; sect++ ) {
var sectpos = rowpos + sect * sectsize;
for ( var col = 0; col < 256; col++ ) {
var colpos = sectpos + col * 4;
var snext = (sect + 1) % 6;
var fright = col * one256;
var fleft = 1 - fright;
var sr = r[sect];
var sg = g[sect];
var sb = b[sect];
var srn = r[snext];
var sgn = g[snext];
var sbn = b[snext];
var cr = (sr * fleft + srn * fright) * 255 | 0;
var cg = (sg * fleft + sgn * fright) * 255 | 0;
var cb = (sb * fleft + sbn * fright) * 255 | 0;
img.data[colpos + 0] = cr;
img.data[colpos + 1] = cg;
img.data[colpos + 2] = cb;
img.data[colpos + 3] = 255;
}
}
}
ct.putImageData(img, 0, 0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.