Four Bugs

canvasmathanimation

Although this gist is not exactly the four bug problem (where bugs/mice/insects are placed at the corners of a regular polygon, and each bug then begins to move towards its immediate neighbour in an counter-clockwise direction), it started out with that intention. Instead, because the angles are quite shallow and the lines close together, an interesting interference sub-pattern appears as the polygon rotates. Presently the parameters are fixed, but I will make it user configurable as there are many interesting shapes and patterns to be explored.

28 Sept 2014 by rm-hull
rm-hull/0c6393d5092cd656f801
four-bugs.cljs
(ns enchilada.four-bugs
  (:require
    [jayq.core :refer [show]]
    [big-bang.core :refer [big-bang]]
    [enchilada :refer [canvas ctx value-of]]
    [monet.canvas :refer [translate scale rotate
                          save restore fill-rect
                          stroke-style stroke fill-style fill
                          begin-path close-path move-to line-to]]))

(defn draw-polygon [ctx n r]
  (->
    ctx
    (fill-style :white)
    (stroke-style :black)
    (begin-path)
    (move-to r 0))

  (dotimes [i n]
    (let [theta (/ (* i 2 Math/PI) n)]
      (line-to ctx (* r (Math/cos theta)) (* r (Math/sin theta)))))
  (->
    ctx
    (close-path)
    (fill)
    (stroke)))

(defn draw-shapes [ctx n r decr angle]
  (if (pos? r)
    (recur
      (-> ctx (draw-polygon n r) (rotate angle))
      n
      (- r decr)
      decr
      angle)
    ctx))

(def initial-state
  {:t 0
   :radius 290
   :angle 0.01
   :sides 4
   :decrement 3.61})

(defn update-state [event world-state]
  (update-in world-state [:t] inc))

(defn render [{:keys [t angle radius sides decrement] :as world-state}]
  (->
    ctx
    (save)
    (fill-style :lightgreen)
    (fill-rect {:x 0 :y 0 :w 800 :h 600})
    (translate 400 300)
    (rotate (* t 0.005))
    (draw-shapes sides radius decrement angle)
    (restore)))

(show canvas)
(big-bang
  :initial-state initial-state
  :on-tick update-state
  :to-draw render)