Gradient Orientation Javascript
A solution to draw strokes in Javascript based on gradient orientation. Uses p5.js.
HTML
<script src="http://cdn.jsdelivr.net/p5.js/0.3.9/p5.min.js"></script>
<img src="http://lorempixel.com/300/400/people/2" />
CSS
img, canvas {
float: left;
}
JavaScript
/* NOTE: IF CHROME IS BLOCKING THE IMAGE, TRY WITH ANOTHER BROWSER */
var img, vectors;
var pixelsToSkip = 2; // for faster rendering we can stroke less lines
var linesLength = 20;
var strokeThickness = 1;
function preload() {
img = loadImage('http://lorempixel.com/300/400/people/2');
img2 = loadImage('http://lorempixel.com/300/400/people/2');
/* you can test in local if the directions are correct using a simple gradient as image
img = loadImage('http://fornace.io/jstests/img/gradient.jpg');
img2 = loadImage('http://fornace.io/jstests/img/gradient.jpg');
*/
}
function setup() {
createCanvas(img.width, img.height);
noLoop();
img.loadPixels();
makeLumas();
makeGradients();
makeVectors();
for ( var xx = 0; xx < img.width; xx = xx + pixelsToSkip) {
for ( var yy = 0; yy < img.height; yy = yy + pixelsToSkip) {
push();
linesLength = vectors[yy][xx].mag*200+random(0,4);
stroke(random(255),vectors[yy][xx].mag*100); // to color with pixel color change to stroke(img.get(xx, yy)), or vectors[yy][xx].mag;
strokeWeight(strokeThickness);
translate(xx,yy);
rotate( vectors[yy][xx].dir + PI/2 ); // here we use the rotation of the gradient. i inverted it so the strokes are more powerful where strong differences are.
line(-linesLength/2, 0, linesLength/2, 0);
pop();
}
}
// adding the image in overlay to evaluate if the map is good
// tint(255, 255, 255, 200);
// image(img2,0,0);
}
function draw() {
}
function makeLumas() {
// calculate the luma for each pixel to get a map of dark/light areas ("Rec. 601") https://en.wikipedia.org/wiki/Luma_(video)
lumas = new Array(img.height);
for (var y = 0; y < img.height; y++) {
lumas[y] =...