Pixelart using Javascript

Pixelart using Javascript

Image source: Self Made

Summary

I was surfing a bit on twitter and found a very nice tweet regarding generating of pixel art like pattern. The original post regarded python code, but I found a provided javascript code block even more interisting as it can be tried out directly in any modern browser without further installations.

Canvas

A canvas is an area on a web site that can be added using the <canvas> HTML Tag. On this canvas we can draw a lot of primitive objects like lines and rectangles. Each canvas needs two dimensions, their height and the width. To create an empty canvas, just use:

<canvas id="example" width="800" height="600"></canvas>

and than you can use javascript to draw something on this canvas.

const context = example.getContext('2d')
// parameters: x, y, sizeX, sizeY
context.fillRect(0, 4, 8, 16)

I created an small example that you can run by pressing the Draw Box example.

The canvas can be seen as a Matrix with color values in each row / column combination. The default color is white, and with any further settings the default is to write in pure black on the canvas.

Functions

The general idea is to draw on a canvas having x and y coordinates, what gives us two input parameters for functions.

Note: Instead of having x,y = 0,0 in the lower left corner, canvas have 0,0 at upper left corner.

We will be using following function for example (the header image uses this settings):

f(x, y) = (xy)modulo(9)

I wanted to pass the function in a input box and let the user play around with it. For evaluate the function I tried the eval function from javascript - but is slow for this purpose. Thats why I will provide 3 canvas to let you play around with it, having two different functions and a general one to play around, using eval.

(x ^ y % MOD)

This uses the Exponent function and the modulo to generate the pattern. Just add the module value and trigger the button to play with this type of functions.

(x ^ y) %

Try following modulo values:

  • 5
  • 9
  • 17
  • 33

(x | y % MOD)

This function use the binary OR operator. The resulting images have rectangle triangles.

(x | y) %

Following values are worth to try out:

  • 7
  • 17
  • 29

Functions

With this, you can pass any function and eval will try to extract 0/1 out of it. This required valid javascript syntax and is really slow compared to the solutions provided.

Try out:

  • (x * y) & 47
  • (x * 31) % y
  • ((x-128) * 64) % (y-128)

Code

You can check out the source code on my github page for less code from the acuat blog, without any external code dependency. https://github.com/dariusgm/pixelart

More

You can find more informations here: