Created
February 27, 2015 02:33
-
-
Save winkerVSbecks/62abcd20112cb8f2a5d2 to your computer and use it in GitHub Desktop.
Paper JS Vector Field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
paper.install(window); | |
var canvas, parent, hero, mousePos; | |
var locs = []; | |
var paths = []; | |
var thetas = []; | |
var nodes = 0; | |
window.onload = function() { | |
paper.setup('js-vector-field'); | |
canvas = document.getElementById('js-vector-field'); | |
hero = document.getElementsByClassName('hero')[0]; | |
parent = canvas.parentNode; | |
mousePos = paper.view.center; | |
init(); | |
// Draw! | |
paper.view.draw(); | |
paper.view.onFrame = function(event) { | |
// animateVectors(); | |
}; | |
}; | |
var init = function() { | |
project.clear(); | |
// Resize View | |
var h = hero.offsetHeight; | |
var w = hero.offsetWidth; | |
canvas.width = w; | |
canvas.height = h; | |
parent.style.width = w + 'px'; | |
parent.style.height = h + 'px'; | |
view.viewSize = new Size(w, h); | |
var background = new Path.Rectangle(view.bounds); | |
background.fillColor = '#fe5b64'; | |
buildVectors(); | |
}; | |
window.onresize = init; | |
var buildVectors = function() { | |
var res = 20; | |
var countX = Math.ceil(paper.view.size.width/res) + 1; | |
var countY = Math.ceil(paper.view.size.height/res) + 1; | |
for (var j = 0; j < countY; j++) { | |
for (var i = 0; i < countX; i++) { | |
paths.push(new Path.Line({ | |
from: [-res + res*i, res*j], | |
to: [-res + res*i, res*j - 15], | |
strokeColor: '#ffffff', | |
strokeWidth: 2, | |
opacity: 0.294117647 | |
})); | |
locs.push(new Point([-res + res*i, res*j])); | |
} | |
} | |
nodes = paths.length - 1; | |
}; | |
var animateVectors = function() { | |
for (var i = nodes; i >= 0; i--) { | |
var p = paths[i].segments[0].point; | |
var dir = calcVec(p.x - mousePos.x, p.y - mousePos.y); | |
var theta = p.getDirectedAngle(dir); | |
if (!thetas[i]) { | |
thetas.push(theta); | |
} else { | |
paths[i].rotate(-thetas[i], p); | |
thetas[i] = theta; | |
} | |
paths[i].rotate(theta, p); | |
}; | |
}; | |
var calcVec = function(x, y) { | |
return new Point([y - x, - x - y]); | |
} | |
window.onmousemove = function(event) { | |
mousePos.x = event.x; | |
mousePos.y = event.y; | |
animateVectors(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment