This code provides a simple example of how to build an ImageData object from text art that can be used in a canvas.
Created
June 10, 2015 15:19
-
-
Save rob-blackbourn/651442b0af365a0e9ffb to your computer and use it in GitHub Desktop.
Build ImageData from text art in Javascript
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
/*jshint browser: true*/ | |
(function () { | |
var myPalette = { | |
' ': [255, 255, 255, 255], // white | |
'#': [255, 0, 0, 255] // red | |
}; | |
var myTextArt = [ | |
"## ##", | |
" ## ## ", | |
" ## ## ", | |
" ## ## ", | |
" ### ", | |
" ## ## ", | |
" ## ## ", | |
" ## ## ", | |
"## ##"]; | |
function makeImageData(context2d, palette, textArt, scaleX, scaleY) { | |
var rows = textArt.length; | |
var columns = textArt[0].length; | |
var imageData = context2d.createImageData(columns * scaleX, rows * scaleY); | |
for (var row = 0, index = 0; row < rows; ++row) { | |
for (var x = 0; x < scaleX; ++x) { | |
for (var column = 0; column < columns; ++column) { | |
for (var y = 0; y < scaleY; ++y) { | |
var character = textArt[row][column]; | |
var colour = palette[character]; | |
imageData.data.set(colour, index); | |
index += 4; | |
} | |
} | |
} | |
} | |
return imageData; | |
} | |
function start() { | |
var canvas = document.getElementById("myCanvas"); | |
var context2d = canvas.getContext("2d"); | |
var imageData = makeImageData(context2d, myPalette, myTextArt, 2, 2); | |
context2d.putImageData(imageData, 20, 20); | |
} | |
window.addEventListener('load', start); | |
})(); |
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> | |
<body> | |
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;"> | |
Your browser does not support the HTML5 canvas tag. | |
</canvas> | |
<script src="image.js"></script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment