Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to create a bitmap/canvas image from binary 1's and 0's to visually see the data in JavaScript?

Let's say I have 20,164 binary digits in a standard JavaScript string, for example:

var data = '101010101010101010101010100110001011010101101' ...

What I want to do is see a visual representation of these digits by converting it to a bitmap or perhaps HTML5 canvas image. So if I loop through all the bits and it comes across a 1 it will draw a black pixel, and a 0 the pixel will be white.

So I'm guessing I'll need a 142 x 142 pixel grid something which looks like this:

binary data bitmap

What's an algorithm or way to do this in JavaScript? All I need to do is display it on the web page so maybe creating a basic bitmap or canvas or SVG image will be fine.

Many thanks

like image 987
user2503552 Avatar asked Dec 07 '22 06:12

user2503552


1 Answers

You're exactly correct with the HTML5 canvas idea. You could try something like the following if you don't want to do base64 data.

Javascript (with no error checking):

var string = "1010101...";
var ctx = document.getElementById("canvas").getContext('2d');
ctx.fillStyle = "#FFF";  // Fill with white first
ctx.fillRect(0, 0, 142, 142);
ctx.fillStyle = "#000";
for (var i = 0; i < 142; i++) {  // Loop through each character
    for (var j = 0; j < 142; j++) {
        if (string[i*142+j] == '1')     // If the character is one,
            ctx.fillRect(i, j, 1, 1 );  // fill the pixel with black
    }
}

HTML:

<body>
    <canvas width=142 height=142 id="canvas"></canvas>
</body>

If you use this, you should make sure to check that the length of the string is the length you are expecting.

like image 55
Matt Bryant Avatar answered Dec 08 '22 19:12

Matt Bryant