14th August, 2014

Vector Field

See the Pen Vector Field by Varun Vachhar (@winkerVSbecks) on CodePen.

While going through the Google Material Design handbook the illustration in the Users Initiate Change caught my eye. Around the same time p5js was announced, so I figured it would be fun replicating this with Canvas.

My first attempt was to build a grid of vectors and then rotate them towards the mouse location. The rotation would be scaled down based on the distance from the mouse location, i.e: rotation = angle * scale(0, 1, 0, width-of-the-canvas). This gave an interesting result but, it wasn’t quite the same spiral effect.

The next step was to look into how vector fields work. With a bit of help from Paul’s Online Math Notes, Wolfram Alpha and math.stackexchange.com I discovered that: f(x,y) = [(y−5)-(x−5), -(x−5)-(y−5)] produces the exact spiralling effect.

Building this with p5js was fairly straightforward. Processing has an awesome drawing API and p5js brings it to the web. If you are interested in getting started with p5js I have built a seed project. There are some great tutorials on the project site and Daniel Shiffman has ported his amazing The Nature of Code Examples to p5js too.

for (var i = locs.length - 1; i >= 0; i--) {
  var h = calcVec( locs[i].x - mouseX, locs[i].y - mouseY);
    locs[i].x + 15*cos(h.heading()),
    locs[i].y + 15*sin(h.heading())

Questions, Comments or Suggestions? Open an Issue