Created
January 21, 2015 06:42
-
-
Save evitolins/52cd88eda421438b71ab to your computer and use it in GitHub Desktop.
Canvas Pixel Renderer: http://jsbin.com/aLehEdug/3/edit?html,css,js,output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Pixel Data | |
var pixel = 10; | |
var pixels = [ | |
[0,0,0,0,0,0,0,1,0,0], | |
[1,0,0,0,0,0,0,0,3,0], | |
[0,0,1,0,0,0,0,1,0,0], | |
[0,0,0,0,1,0,0,1,0,0], | |
[1,1,0,0,0,1,0,0,0,0], | |
[0,0,0,0,0,2,0,0,1,0], | |
[2,0,1,0,0,0,0,0,1,0], | |
[0,0,0,0,3,0,0,0,0,0], | |
[0,1,0,0,0,0,1,0,0,0], | |
[1,2,0,1,0,0,0,0,0,1] | |
]; | |
// Setup Canvas | |
var canvas = document.getElementById('canvas'); | |
var context = canvas.getContext('2d'); | |
canvas.width = (pixels.length) * pixel; | |
canvas.height = (pixels[0].length) * pixel; | |
// Renderer | |
var render = function(pixels){ | |
var x,y,i,ii; | |
for (i=0; i<pixels.length; i++) { | |
for (ii=0; ii<pixels[i].length; ii++) { | |
x = ii * pixel; | |
y = i * pixel; | |
// Skip 'blank' pixel | |
if (pixels[i][ii] === 0) { | |
continue; | |
} | |
// Choose pixel color and draw | |
context.beginPath(); | |
if (pixels[i][ii] === 1) { | |
context.fillStyle = 'red'; | |
} | |
if (pixels[i][ii] === 2) { | |
context.fillStyle = 'green'; | |
} | |
if (pixels[i][ii] === 3) { | |
context.fillStyle = 'blue'; | |
} | |
context.rect(x, y, pixel, pixel); | |
context.fill(); | |
} | |
} | |
}; | |
render(pixels); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset=utf-8 /> | |
<title>JS Bin</title> | |
</head> | |
<body> | |
<canvas id="canvas" width=100 height=100></canvas> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
canvas { | |
border: 1px solid #aaa; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment