Constrain: Constraint-Based Animated Figures

Constrain:

Constraint-Based Animated Figures
Andrew Myers

Constrain

Constrain

  • Declarative constraint-based description
  • Figure can have multiple key frames
  • Attributes can be animated within a frame
  • Graphical content can constrain against HTML content

Rendering capabilities

  • Standard graphical objects: rectangles, lines, circles
  • Automatic connectors support diagrams
  • Automatic text layout
  • Constraint-based ⇒ responsive to display changes, font availability

Programming with Constrain

  • Web page can hold multiple Figures, each tied to a canvas.
    <canvas id=canv1></canvas>
    fig = new Figure("canv1")
  • Graphical objects created declaratively using builder pattern:
    with (fig) {
      s = square().setFillStyle("yellow").setLineWidth(3)
  • Graphical objects introduce variables for their position:
    • .x() : x position (min/max: .x0(), .x1()
    • .y() : y position (min/max: .y0(), .y1()
    • .w() : width, .h() : height
  • Variable values determined by solving constraints:
      equal(s.w(), 150)    // w = 150
      equal(s.x0(), s.w()) // x0 = w
      equal(s.y0(), times(2, s.h())) // y0 = 2*h
  • Convenience methods for alignment constraints, etc.
      let t = ellipse().setFillStyle("#8f8")
      align("abut", "top bottom", s, hspace(100), t)
      align("right", "none", t, canvasRect()) // t.x1 == canvas.x1
                

Examples

Automatic Graph Layout

Extensible

  • Full power of JavaScript 2D canvas rendering
  • Can add/modify graphical objects

Implementation

  • Everything done online in JavaScript (~6k LoC ECMAScript 6)
  • Constraint declarations generate a cost function
    • Less fragile for overconstrained problems
    • Can optimize placement with costs
  • Constraints “solved” by minimizing cost
    • Derivatives computed with backpropagation
    • Gradient descent is way too slow!
    • Uses second-order algorithm: BFGS
    • Constraints automatically partitioned into components, simplified using substitution
  • Animations solved incrementally from previous solution, with adaptive tweening to increase frame rate
  • Text layout: dynamic programming ala TeX

For more information