Skip to content

Commit

Permalink
adds readme docs and an example for setPixel
Browse files Browse the repository at this point in the history
  • Loading branch information
EyalAr committed Nov 29, 2014
1 parent 8615f1f commit 03d1782
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 0 deletions.
19 changes: 19 additions & 0 deletions README.md
Expand Up @@ -30,6 +30,7 @@
0. [Fade (adjust transparency)](#fade)
0. [Opacify](#opacify)
0. [Paste](#paste)
0. [Set pixel](#set-pixel)
0. [Getters](#getters)
0. [Width](#width)
0. [Height](#height)
Expand Down Expand Up @@ -468,6 +469,24 @@ Paste an image on top of this image.
0. Extra caution is required when using this method in batch mode, as the images
may change by the time this operation is called.

#### Set Pixel

Set the color of a pixel.

`image.setPixel(left, top, color, callback)`

0. `left, top {Integer}`: Coordinates of the pixel from the left-top corner of
the image.
0. `color {String / Array / Object}`: Color of the pixel to set.
See [colors specification](#colors-specification).
0. `callback {Function(err, image)}`

**Notes:**

0. If the coordinates exceed the bounds of the image, an exception is thrown.
0. Extra caution is required when using this method in batch mode, as the
dimensions of the image may change by the time this operation is called.

### Getters

#### Width
Expand Down
73 changes: 73 additions & 0 deletions examples/set_pixel.js
@@ -0,0 +1,73 @@
/**
* Example for using LWIP to manually setting pixels in an image.
*
* Creates a canvas with a rainbow gradient.
*/

var path = require('path'),
lwip = require('../');

var output = 'rainbow.png',
width = 360,
height = 360,
color = {h: 0, s: 100, l: 50};

function nextColor(){
color.h++;
if (color.h > 360) color.h = 0;
return hslToRgb(color);
}

// create an empty image canvas
lwip.create(width, height, function(err, image){
if (err) return console.log(err);

var x, y, c,
batch = image.batch();

// set the same color for each columns in the image
for (x = 0; x < width ; x++){
c = nextColor();
for (y = 0; y < height; y++){
batch.setPixel(x, y, c);
}
}

batch.writeFile(output, function(err){
if (err) console.log(err);
});
});

// adapted from http://stackoverflow.com/a/9493060/1365324
function hslToRgb(hsl){
var h = hsl.h / 360,
s = hsl.s / 100,
l = hsl.l / 100;

var r, g, b;

if(s == 0){
r = g = b = l; // achromatic
}else{
function hue2rgb(p, q, t){
if(t < 0) t += 1;
if(t > 1) t -= 1;
if(t < 1/6) return p + (q - p) * 6 * t;
if(t < 1/2) return q;
if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}

var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}

return {
r: Math.round(r * 255),
g: Math.round(g * 255),
b: Math.round(b * 255)
};
}

0 comments on commit 03d1782

Please sign in to comment.