Using Canvas in HTML5

For my Art History class on Modern Art, I created a work of Conceptual Art. This work of post-modernist theory explores a non-determinist approach to building a unique creation. The method abstracts the input of the artist, who creates a framework for the piece and then sets in motion the process which completes it. This particular work, called “Orbs”, uses the new HTML5 canvas to create a random number of randomly sized and colored circles in the webpage on each page load. Due to the large number of random elements no two views of the art work should repeat.

http://www.rnuckolls.com/concept.html

The body of the page is quite simple.

<body onload="loadShapes();">
   <canvas id="mycanvas"></canvas>
</body>

The javascript does all the randomizing and painting of the canvas.

<script type="text/javascript">
function loadShapes(){
  drawShape(getRandomArbitary(20,50));
}
function getRandomArbitary (min, max) {
    return Math.random() * (max - min) + min;
}
function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}
function drawShape(count){
  // get the canvas element using the DOM
  var canvas = document.getElementById('mycanvas');

  // Make sure we don't execute when canvas isn't supported
  if (canvas.getContext){

    // use getContext to use the canvas for drawing
    var ctx = canvas.getContext('2d');

  var w = screen.availWidth-30;
  var h = screen.availHeight-100;

  var rand1 = getRandomArbitary(0,w);
  var rand2 = getRandomArbitary(0,h);
  var rand3 = Math.round(getRandomArbitary(10,50));
  var color1 = "#" + Math.round(getRandomArbitary(111111,999999));
  var color2 = "#" + Math.round(getRandomArbitary(111111,999999));
  var colorRGB = "rgba(" + hexToRgb(color1).r +","+ hexToRgb(color1).g +","+ hexToRgb(color1).b + ",0)";
  var radgrad = ctx.createRadialGradient(rand1,rand2,rand3,rand1+7,rand2+5,rand3+20);

    ctx.canvas.width = w;
    ctx.canvas.height = h;

  for (var i=0;i<count;i++){
    // Create gradients
    radgrad.addColorStop(0, color1);
    radgrad.addColorStop(0.9, color2);
    radgrad.addColorStop(1, colorRGB);
    // draw shapes
    ctx.fillStyle = radgrad;
    ctx.fillRect(0,0,w,h);
    rand1 = getRandomArbitary(0,w);
    rand2 = getRandomArbitary(0,h);
    rand3 = Math.round(getRandomArbitary(10,50));
    color1 = "#" + Math.round(getRandomArbitary(111111,999999));
    color2 = "#" + Math.round(getRandomArbitary(111111,999999));
    radgrad = ctx.createRadialGradient(rand1,rand2,rand3,rand1+7,rand2+5,rand3+(Math.round(rand3*1.5)));
  }

  } else {
    alert('You need Safari or Firefox 1.5+ to see this demo.');
  }
}
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *