Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <section id="content">
  <canvas id="canvas"></canvas>
</section>

<section id="about">
  <div id="about-title">Fast Animated Fractal - FINAL WORK</div>
  <div id="about-author">an experimentation by François Chazal (<a href="https://www.twitter.com/fchazal">@fchazal</a>)</div>
  
  <div id="about-button" class="start">START COMPUTATION</div>
</section>

<section id="console">CONSOLE</section>

<!-------------------------------->

<script id="fractal-worker" type="javascript/worker">
 	
/* BEGINNING OF LOADING BLOCK ****************/

self.onmessage = function(event) {
  var message = event.data;

  switch (message.action) {
    case 'init':
      DeJong.init(message.size);
      break;

    case 'toggle':
      DeJong.toggle();
      break;
      
    case 'send':
      DeJong.send();
      break;
      
    case 'update':
      DeJong.reset();
      DeJong.iteration = 0;
      DeJong.a = message.a;
      DeJong.b = message.b;
      DeJong.c = message.c;
      DeJong.d = message.d;
      DeJong.loop_steps = message.steps;
      DeJong.loop_speed = (1000 - message.speed);
      
      DeJong.animate = message.animate;
      DeJong.var_a = message.var_a;
      DeJong.var_b = message.var_b;
      DeJong.var_c = message.var_c;
      DeJong.var_d = message.var_d;
      
    default:
  }
}

/* END OF LOADING BLOCK **********************/
 

/* ELEMENT : Fractal
**********************************************/

var DeJong = {
  iteration: 0,
  a: 1.4, b: -2.3, // x[n+1] = sin(a y[n]) - cos(b x[n])
  c: 2.4, d: -2.1, // y[n+1] = sin(c y[n]) - cos(d x[n])

  animate: false,
  var_a: 0.0, var_b: 0.0,
  var_c: 0.0, var_d: 0.0,
  
  loop: false,
  loop_speed: 1,
  loop_steps: 100000,
  
  size: 0,
  zoom: 0,
  point: { x: 0, y: 0 },
  center: { x: 0, y: 0 },
   
  buffer: null,
  histogram: null,  

  init: function(size) {
    this.size = size;
    this.zoom = this.size / 4;
    this.center.x = this.center.y = this.size / 2;

    this.buffer = new Uint16Array(this.size * this.size);
    this.histogram = new Uint32Array(1 << 16);
    this.histogram[0] = this.buffer.length;
  },
  
  toggle: function() {
    this.loop = !this.loop;
    this.run();
  },

  run: function() {
    if (this.animate) this.reset();
    
    for (var i=this.loop_steps; 0 < i--; ) {
      this.point = this.compute(this.point);
      
      var x = Math.floor(this.center.x + this.point.x * this.zoom);
      var y = Math.floor(this.center.y - this.point.y * this.zoom);

      var index = (y * this.size + x);
      
      this.histogram[this.buffer[index]]--;
      this.histogram[++this.buffer[index]]++;
    }

    if (this.animate) {
      this.a += this.var_a; 
      this.b += this.var_b; 
      this.c += this.var_c; 
      this.d += this.var_d; 
    }

    if (this.loop) setTimeout(function() { DeJong.run(); }, this.loop_speed);
  },
    
  reset: function() {
    for (var i=0; i<this.buffer.length; i++) this.buffer[i] = 0;
    for (var i=0; i<this.histogram.length; i++) this.histogram[i] = 0;
    this.histogram[0] = this.buffer.length;
  },

  compute: function(point) {
    this.iteration++;
    return {
      x: Math.sin(this.a * point.y) - Math.cos(this.b * point.x),
      y: Math.sin(this.c * point.x) - Math.cos(this.d * point.y)
    };
  },
  
  send: function() {
    self.postMessage({
      buffer: this.buffer,
      histogram: this.histogram,
      iteration: this.iteration,
      parameters: [this.a, this.b, this.c, this.d]
    });
  }
};
</script>
              
            
!

CSS

              
                @import "compass/css3";

@import url(https://fonts.googleapis.com/css?family=Roboto+Condensed:300italic,400italic,700italic,400,300,700);

html { font-size: 11px; }

body {
	overflow: hidden;
  min-height: 100%;
  font: 1em/1.5em 'Roboto Condensed', sans-serif;
}

a { text-decoration: inherit; color: inherit; }

#content {
  position: fixed;

  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  
  #canvas {
    width: 100%;
    height: 100%;
    
    background: #222;
  }
}


#about {
  position: fixed;

  left: 0px;
  bottom: 0px;
  width: 100%;
  height: 50px;
  
  color: #fff;
  
  background: rgba(0,0,0,0.8);
}

#about-title {
  position: absolute;
  
  left: 25px;
  bottom: 25px;
  
  font-size: 2em;
  font-weight: 700;
}

#about-author {
  position: absolute;
  
  left: 25px;
  top: 27px;
  
  font-size: .9em;
  font-weight: 300;
}

#about-button {
  position: absolute;
  
  top: 0px;
  right: 0px;
  
  padding: 0px 10px;
  margin: 10px;
  
  color: #fff;
  font-size: 1.1em;
  font-weight: 700;
  line-height: 30px;
  
  border-radius: 3px;
  
  cursor: pointer;
  
  &.start { background: #080;  }
  &.start:hover { background: #0c0; }
  
  &.stop { background: #800; }
  &.stop:hover { background: #c00; }
}

#console {
  position: absolute;
  
  top: 0px;
  left: 0px;
  width: 100%;
  padding: 5px 10px;
  
  color: #fff;
  font-size: 1em;
  font-style: italic;
  font-weight: 300;
}

              
            
!

JS

              
                /* REQUIREMENTS ******************************/

requireScripts(
  [
    'https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.5.1/dat.gui.js'
  ], load
);

addEvent(window, "DOMContentLoaded", load);

/* BEGINNING OF LOADING BLOCK ****************/

var v = 0;
function load() {
  if (++v != 2) return; // wait for DOM and SCRIPTS

  Console.init('#console');  

  Global.init();
  Fractal.init();
  Canvas.init('#canvas');
  
  Fractal.call();
}

/* END OF LOADING BLOCK **********************/


/* ELEMENT : Global
**********************************************/

var Global = {
  gui: null,
  engine: null,

  // Display
  equalize: false,
  factor: 2,
  color: '#ffaa11',
  
  // Computation
  speed: 1000,
  steps: 100000,
  a: '1.4', b: '-2.3', // x[n+1] = sin(a y[n]) - cos(b x[n])
  c: '2.4', d: '-2.1', // y[n+1] = sin(c y[n]) - cos(d x[n])
  
  // Animation
  animate: true,
  var_a: 0.1, var_b: 0.1,
  var_c: 0.1, var_d: 0.1,
  toggle: function() { },
  
  init: function() {
    this.gui = new dat.GUI({ autoPlace: true });
    this.gui.domElement.id = 'parameters';
   
 
    this.gui.add(Global, 'animate').name('Animate').onFinishChange(Global.update);;
    this.gui.add(Global, 'equalize').name('Equalize');
    this.gui.add(Global, 'factor',1,10).step(0.1).name('Equalize factor');
    this.gui.add(Global, 'speed',0,1000).name('Speed factor').onFinishChange(Global.update);
    this.gui.addColor(Global, 'color').name('Fractal color');
    
    var computation = this.gui.addFolder('Computation parameters');
    computation.add(Global, 'a').name('Value of A').listen().onFinishChange(Global.update);
    computation.add(Global, 'b').name('Value of B').listen().onFinishChange(Global.update);
    computation.add(Global, 'c').name('Value of C').listen().onFinishChange(Global.update);
    computation.add(Global, 'd').name('Value of D').listen().onFinishChange(Global.update);
    computation.add(Global, 'steps').name('Dots by step').onFinishChange(Global.update);
    
    var animation = this.gui.addFolder('Animation parameters');
    animation.add(Global, 'var_a',-1,1).step(0.1).name('Change A by').onFinishChange(Global.update);
    animation.add(Global, 'var_b',-1,1).step(0.1).name('Change B by').onFinishChange(Global.update);
    animation.add(Global, 'var_c',-1,1).step(0.1).name('Change C by').onFinishChange(Global.update);
    animation.add(Global, 'var_d',-1,1).step(0.1).name('Change D by').onFinishChange(Global.update);


    this.engine = Worker.createFromScript('#fractal-worker');
    addEvent(this.engine, 'message', this.processEvent, this);
  },
  
  getColor: function() {
    return parseInt('0x'+
                    this.color.substring(5,7)+
                    this.color.substring(3,5)+
                    this.color.substring(1,3));
  },
  
  update: function() {
    Fractal.reset();
    Global.engine.postMessage({
      action: 'update',

      a: parseFloat(Global.a),
      b: parseFloat(Global.b),
      c: parseFloat(Global.c),
      d: parseFloat(Global.d),

      speed: Global.speed,
      steps: Global.steps,

      animate: Global.animate,

      var_a: Global.var_a * 1e-2,
      var_b: Global.var_b * 1e-2,
      var_c: Global.var_c * 1e-2,
      var_d: Global.var_d * 1e-2,
    });
    Console.log('Parameters updated');
  },

  processEvent: function(e) {
    Fractal.message = e.data; // Stores for later call
    Global.a = e.data.parameters[0];
    Global.b = e.data.parameters[1];
    Global.c = e.data.parameters[2];
    Global.d = e.data.parameters[3];
  }

};


/* ELEMENT : Fractal
**********************************************/

var Fractal = {
  canvas: null,
  canvasCtx: null,
    
  size: 512,
  loop: false,
   
  buffer: null,
  data8: null,
  data32: null,
  histogram: null,
  
  message: null,

  init: function() {
    this.canvas = document.createElement('canvas');
    this.canvas.width = this.size; this.canvas.height = this.size;

    this.canvasCtx = this.canvas.getContext('2d');
    this.canvasCtx.clearRect(0, 0, this.size, this.size);

    this.buffer = new ArrayBuffer(this.size*this.size*4);
    this.data8 = new Uint8Array(this.buffer);
    this.data32 = new Uint32Array(this.buffer);

    this.histogram = new Uint32Array(1 << 16);

    Global.engine.postMessage({ action: 'init', size: this.size });
    Global.update();

    addEvent(document.querySelector('#about-button'), 'click', this.call, this);  
  },
  
  call: function(e) {
    if (this.loop) {
      document.querySelector('#about-button').className = 'start';
      document.querySelector('#about-button').innerHTML = 'START COMPUTATION';
      this.loop = false;
    } else {
      document.querySelector('#about-button').className = 'stop';
      document.querySelector('#about-button').innerHTML = 'STOP COMPUTATION';
      this.loop = true;
    }
    Global.engine.postMessage({ action: 'toggle' });
  },
  
  reset: function() {
    this.canvasCtx.clearRect(0, 0, this.size, this.size);
    for (var i=0; i<this.buffer.length; i++) this.buffer[i] = 0;
    for (var i=0; i<this.histogram.length; i++) this.histogram[i] = 0;
  },

  draw: function() {
    if (this.message == null) return ;
    var data = this.message;

    if (Global.animate) this.reset();
    
    var alpha_max = 0;
    for (var i=0; i < data.histogram.length; i++) {
      if (data.histogram[i] > 0) alpha_max = i;
    }
    
    // Histogram equalization
    var v1 = this.data32.length - data.histogram[0], v2 = 0;
    for (var i=1; i < data.histogram.length; i++) {
      v2 += data.histogram[i];
      this.histogram[i] = 255 * Math.pow(v2 / v1, Global.factor);
    }
    
    var color = Global.getColor();
    var alpha_val = 0;
    
    if (Global.equalize) {
      for (var i=0; i<this.data32.length; i++) {
        alpha_val = this.histogram[data.buffer[i]];
        this.data32[i] = color | (alpha_val << 24);
      }
    } else {
      if (Global.animate) {
        for (var i=0; i<this.data32.length; i++) {
          alpha_val = Math.min(255, 25 * data.buffer[i]);
          this.data32[i] = color | (alpha_val << 24);
        }
      } else {
        for (var i=0; i<this.data32.length; i++) {
          alpha_val = Math.min(255, data.buffer[i]);
          this.data32[i] = color | (alpha_val << 24);
        }
      }
    }
    
    var imageData = this.canvasCtx.getImageData(0, 0, this.size, this.size);
    imageData.data.set(this.data8);
    this.canvasCtx.putImageData(imageData, 0, 0);

    Console.log(data.iteration+' points computed');

    imageData = null;

    data.histogram = null;
    data.buffer = null;
    data = null;

    this.message = null;
  },
}; 


/* ELEMENT : Canvas
**********************************************/

var Canvas = {
  canvas: null,
  canvasCtx: null,
  
  coords : { x: 0, y: 0, w: 0, h: 0 },
  
  init: function(id) {
    this.canvas = document.querySelector(id);
    this.canvasCtx = this.canvas.getContext('2d');
    
    addEvent(window, 'resize', this.resize, this);
    this.resize();
    Console.log('');
  },
 
  resize: function() {
    this.canvas.width = this.canvas.offsetWidth;
    this.canvas.height = this.canvas.offsetHeight;
    
    this.coords.w = this.coords.h = 512;
    // Math.min(this.canvas.width, this.canvas.height);
    this.coords.x = (this.canvas.width-this.coords.w)/2;
    this.coords.y = (this.canvas.height-this.coords.h)/2;
    
    window.requestAnimationFrame(function() { Canvas.render(); });
  },

  render: function() {
    if (Fractal.loop) {
      Global.engine.postMessage({ action: 'send' });
    }
    
    Fractal.draw();

    this.canvasCtx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    this.canvasCtx.drawImage(Fractal.canvas, 0, 0, Fractal.size, Fractal.size, this.coords.x, this.coords.y, this.coords.w, this.coords.h);
    
    window.requestAnimationFrame(function() { Canvas.render(); });
  }
};


/* ELEMENT : Console
**********************************************/

var Console = {
  element: null,
  init: function(id)  { this.element = document.querySelector(id); },
  log: function(html) { this.element.innerHTML = '<b>LOG:</b> '+html; },
  err: function(html) { this.element.innerHTML = '<b>ERROR:</b> '+html; }
}
  

/* LIBRARY : Animation Framerate
***********************************************/

window.requestAnimationFrame = (function() {
  return window.requestAnimationFrame       ||
         window.webkitRequestAnimationFrame ||
         window.mozRequestAnimationFrame    ||
         window.oRequestAnimationFrame      ||
         window.msRequestAnimationFrame     ||
         function (callback) {
           window.setTimeout(callback, 1000 / 60); // smooth transition
         };
})();


/* LIBRARY : WebWorker Management
***********************************************/

Worker.createFromScript = function(id) {
  var URL = window.webkitURL || window.URL;
  var blob = new Blob([document.querySelector(id).textContent]);
  
  return new Worker(URL.createObjectURL(blob));
}


/* LIBRARY : Class Management
***********************************************/

Element.prototype.hasClass = function(cls) {
	return null !== this.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

Element.prototype.addClass = function(cls) {
	if (!this.hasClass(cls)) this.className += " "+cls;
}

Element.prototype.removeClass = function(cls) {
  if (this.hasClass(cls)) {
    var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		this.className = this.className.replace(reg,' ');
	}
}

Element.prototype.toggleClass = function(cls) {
  if (!this.hasClass(cls))
		this.addClass(cls);
	else
		this.removeClass(cls);
}


/* LIBRARY : Requirements Management
***********************************************/

function requireScripts(scripts, callback) {
  for (var id in scripts) {
    var script = document.createElement('script');
    
    script.type = 'text/javascript';
    script.src = scripts[id] + '?' + (new Date().getTime());
    
    if (callback) {
      script.onreadystatechange = callback;
      script.onload = script.onreadystatechange;
    }
    
    document.getElementsByTagName('head')[0].appendChild(script);
  }
}


/* LIBRARY : Event Management
***********************************************/

function addEvent(eventTrigger, eventName, eventHandler, scopeElement) {
	var scopedEventHandler = null;
	
	if (scopeElement !== undefined)
		scopedEventHandler = function(e) { eventHandler.apply(scopeElement, [e]); }
	else
		scopedEventHandler = eventHandler;

  if(document.addEventListener)
    eventTrigger.addEventListener(eventName, scopedEventHandler, false);
  else if(document.attachEvent)
    eventTrigger.attachEvent("on"+eventName, scopedEventHandler);
}

function fireEvent(eventTrigger, eventName, eventData) {
	var evt = null;
	
	if (typeof Event !== 'undefined') {	
		evt = new Event(eventName);
	} else {
		evt = document.createEvent("Event");
		evt.initEvent(eventName, true, true);
	}
  evt.data = eventData;
  eventTrigger.dispatchEvent(evt);
}

              
            
!
999px

Console