Sunday, October 12, 2014

html5 - Drawing a filled circle using for loop example

I made this filled oval drawing example. In the drawcircle function there are two for loops that go from -radius to radius. In that loop there is a formula that checks if the point is in the radius of the circle and then plots a point.

This circle method can be useful for collision detection or drawing filled circles on maps. I found the original code on the java gaming forum.

Paste the code in for instance jsexample.com to see it in action.

<!DOCTYPE html>
<html><body>
<canvas id="myCanvas" width="320" height="240" style="border:1px solid #d3d3d3;">
Use different browser.
</canvas>
<script>
    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");
    var rx = c.width/2;
    var ry = c.height/2;
    var rw = 64;
    var rh = 64;
    var rm = 5;
    gameloop=setInterval(doGameLoop,16);
    window.addEventListener("mousemove",mm,true);
    function doGameLoop(){
        ctx.clearRect(0,0,c.width,c.height);
        drawCircle(rx,ry,10);
    }
    function mm(evt){
        var rect = c.getBoundingClientRect();
        rx = evt.clientX - rect.left;
        ry = evt.clientY - rect.top;
    }
    function drawCircle(x1,y1,rad){
        for(y2=-rad;y2<=rad;y2++){
        for(x2=-rad;x2<=rad;x2++){
            if( (y2*y2+x2*x2) <= rad*rad+rad*0.8){
                x3 = x1+x2;
                y3 = y1+y2;
                ctx.fillRect(x3,y3,1,1);
            }
        }
        }
     }
</script></body></html>

No comments:

Post a Comment