Fun with Trig and Canvas

From Devipedia

Jump to: navigation, search

This page renders an animated, expanding ellipsis of points with pixel positions as text. Don't bother clicking if you use IE or a browser that does not support the HTML 5 canvas element.

See the result here:

http://www.devinvenable.com/static/canvas2/circle.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
    <script src="./js/jquery-1.3.2.min.js" type="text/javascript"></script> 
    <script type="text/javascript"> 
        $(function(){
            var canvas  = $('#drawonme')[0];
            canvas.width = $(window).width();
            canvas.height = $(window).height();
 
            var ctx     = canvas.getContext('2d');
           
            // origin offsets 
            var ox = $(window).width()/3;
            var oy = $(window).height()/2;
            
            // angular offset 
            var ao = 55;
 
            // radii
            var rx = 20.0;
            var ry = 30.0;
 
            var steps = 64;
            var angleStep = Math.PI * 2 / steps;
            var a= 0; 
   
            setInterval( renderCircle, 1);
 
            function renderCircle() {
                var canvas  = $('#drawonme')[0];
                ctx.clearRect(0,0,canvas.width,canvas.height);         
                rx++; ry++;
                if (ox++ > canvas.width) {
                    ox = 0;
                    rx = 0;
                    ry = 0;
                }
 
                for(a=0; a < steps; a++) { 
                    var x = Math.sin(a * angleStep + ao) * rx + ox 
                    var y = Math.cos(a * angleStep + ao) * ry + oy
     
                    ctx.beginPath();
                    ctx.fillText(x + ", " + y, x, y);
                    ctx.stroke();
                }
            } 
        });
    </script> 
</head> 
<body> 
    <canvas id="drawonme" style="position: absolute; top: 0; left: 0;">If your browser supported the canvas element you'd see graphics instead of this boring message.</canvas>  
</body> 
</html> 
Personal tools