Passion
Pixelart was always my passion. From the earliest childhood when I played Robbo on Atari PC. I want to play with it right in this blog. This article would tell a story about implementing a simple pixelart engine.
Colors
It is handy to write colors in the Hex format, and JavaScript already have syntax for it.
So red would look like 0xFF0000
. I do not know why, but ImageData in canvas stores data bytes in opposite order: Blue-Green-Red-Alpha.
Blog
Now I can just #!pixelart
at the beginning of the js
code in my blog, and it would automatically instantiate the engine and execute the code!
I can specify width
, height
, and points per pixel
for it.
Optimization
I use canvas.context.imageData
for fast access to the raw pixel data.
For optimization purpose I use a technic similar to Double Buffer
and have two Uint32Array
(current
and last
). When point
function is called — it just modify the current
Array.
When the time to draw comes each point from current
is compared to the last
and if it differs — real pixel draw is called.
Real put pixel
On the initialization of the canvas I define a function that takes x
, y
and color
and put them to the imageData.data
. It is not just a trivial assign because of the pixelPerPoint
property.
When this was implemented
image-rendering
for canvas was not supported by major browsers
Generated function for engine initialized with pointsPerPixel = 3
and width = 96
should color 9 real pixels and looks like this:
_drawPoint = function(data, offset, c){
data[offset+0] = data[offset+1] = data[offset+2] =
data[offset+96] = data[offset+97] = data[offset+98] =
data[offset+192] = data[offset+193] = data[offset+194] = c;
}
All colors are converted in such a way that they can be placed directly as a Uint32 value.
In Uint8Array
canvas data is placed as [blue, green, red, alpha], so for Uint32 I need to swap the Red
and Blue
values:
Used bit manipulations to convert the Hex color:
color = ( ( color & 0xff0000 ) >> 16 ) +
( color & 0x00ff00 ) +
( ( color & 0x0000ff ) << 16 )
Lets put some pixels!
// R, G, B in hex
[0xff0000, 0x00ff00, 0x0000ff]
.forEach(function(color, y){
// from 0 to canvas width
for(var x = y; x < w; x += 2){
// put colored point
point(x, y, color);
}
});
point(10, 10, 0xff00ff);
Useful notes
style
variable is exported. style.background = '#FFFFFF';
would change canvas background to the white.
Updated to support calculations and named config:
#!pixelart(10*9, 11*9, 2, {update: false, source: false, float: 'right', canvasOnly: true})