Implicit 2D Div Plot

For those of you who kept up with my old site actionsnippet, you may remember a period where I was plotting lots of implicit 2D and 3D equations. Things like:

Circle…
x^2 + y^2 = 1

The Kusner-Schmitt (Tetrahedral Implicit Surface)
(x^2 + 3) (y^2 + 3) (z^2 + 3) – 32 (x y z + 1) = 0

My personal 2D favorite… the Bicuspid:
(x^2 – a^2)(x – a)^2 + (y^2 – a^2)^2 = 0

With a little tweaking the bicuspid looks like this when plotted:


Click to view original actionsnippet post…

Anyway, I was on the subway the other day with my laptop and I wrote this snippet that plots a donut shape using the implicit equation for a circle. The plot is boring looking, but I was curious to see if I could choke any browsers by drawing the plot with 1000s of divs. No such luck, ie6 in virtual box is the slowest running at around 450-500ms – ei9 in virtualBox was faster than firefox on osx… pretty crazy.

The number in the upper left is the milliseconds it takes to draw (refresh a few times to see how well your browser is doing).

Here is main part of the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 window.onload = function(){
 
  var start = new Date().getTime();
 
  // plot donut
  for (var y = -50; y < 50; y++){
    for (var x = -50; x < 50; x++){
      // x^2 + y^2 = 200 to 1000
      var p = x * x + y * y;
      if (p >= 200 && p <= 1000){
        plot(80 + x, 50 + y);
      }
    }
  }
 
  var end = new Date().getTime();
  document.getElementById("time").innerHTML =  end - start;
 
  function plot(x, y){
    var div = document.createElement("div");
    with(div.style){
      position = "absolute";
      left = x + "px";
      top  = y + "px";
      width = "1px";
      height ="1px";
      // ie6 will draw bigger divs if this is not set to a low number
      fontSize = "1px";
      backgroundColor = "black";
    }
    document.body.appendChild(div);
  }
}

A few things to note about this code, inlining the plot function and making a few other optimization would speed things up a bit I think, but I wanted to keep it semi-readable. The well known javascript guru Douglas Crockford says that with statements are evil. I guess I agree with him after reading what he says about them, but I still can’t resist using them – especially on small demos like this.



 
 
 

Leave a Reply

Spam protection by WP Captcha-Free