Animierte Kreissegmente

Gespeichert von Erik Wegner am/um
Body

Zur Darstellung von Anteilen eigenen sich Kreisdiagramme. Damit sie nicht einfach nur erscheinen, sorgt das folgende Script für ein wenig Animation beim Aufbau.


Your browser does not support the HTML5 canvas tag.

(function() {
  "use strict";
  function ColorValue(color, value) {
    this.color = color;
    this.value = value;
  }
  var drawing = false; // Verhindere gleichzeitigen Aufruf
  
  function draw() {
    var data = [];
    if (drawing) return;
    drawing = true;
    
    data.push(new ColorValue("#382c1a", 10 + parseInt(Math.random()*50)));
    data.push(new ColorValue("#086782", 10 + parseInt(Math.random()*20)));
    data.push(new ColorValue("#cc8722", 10 + parseInt(Math.random()*50)));
    data.push(new ColorValue("#a3a3a3", 10 + parseInt(Math.random()*50)));
    data.push(new ColorValue("#779125", 10 + parseInt(Math.random()*50)));
    data.push(new ColorValue("#ad6600", 10 + parseInt(Math.random()*50)));

    var sum = 0, sumCounter = 0, datalen = data.length, i;
    for (i = 0; i < datalen; i++) {
      sum += data[i].value;
    }

    var center_x = 75, center_y=75, radius = 50, angle1, angle2;

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.lineWidth=20;
    ctx.clearRect(0, 0, c.width, c.height);

    function drawNext() {
      sumCounter++;
      angle1 = Math.PI * (0.5 - sumCounter/sum);
      for (i = 0; i < datalen; i++) {
        angle2 = angle1 + (2 * Math.PI * data[i].value * sumCounter / sum / sum);
        ctx.strokeStyle=data[i].color;
        ctx.beginPath();
        ctx.arc(center_x, center_y, radius, angle1, angle2);
        ctx.stroke();
        angle1 = angle2;
      }
      if (sumCounter < sum) {
        window.setTimeout(drawNext, 15);
      } else {
      	drawing = false;
      }
    }
    drawNext();
  }
  
  draw();
  window.myCanvasButton_Redraw = draw;
})();