Wednesday, January 8, 2014

Drawing circles (and lines, triangles, squares, octagons, etc) with HTML5


<!DOCTYPE html>
<html>
<body>
Step: <input type="text" id="stepValue" value="20"/><br/>
Radius: <input type="text" id="radius" value="50"/><br/>
offset from left: <input type="text" id="h" value="10"/><br/>
offset from top<input type="text" id="k" value="10"/><br/>
clear <input type="checkbox" id="clear" checked/>
<input type="button" value="Draw" onclick="drawCircle();"/><br/>
<canvas id="canvas1" width="220" height="220" style="border:1px solid #c3c3c3;">
Your browser does not support the HTML5 canvas tag.
</canvas>

<script>

function drawCircle(){
var stepParam = parseInt(document.getElementById("stepValue").value);
var radius = parseInt(document.getElementById("radius").value);
var clear = document.getElementById("clear").checked;

var canvas=document.getElementById("canvas1");
   var ctx = canvas.getContext("2d");
if(clear){
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
    //var step = 2*Math.PI/100;
var step = 2*Math.PI/stepParam;
    var r = radius;
    var h = parseInt(document.getElementById("h").value) + r; // offset from left margin, remove r for concentric
    var k = parseInt(document.getElementById("k").value) + r; //offset from top, remove r for concentric

    ctx.beginPath();  //tell canvas to start a set of lines

    for(var theta=0;  theta < 2*Math.PI;  theta+=step)
     { var x = h + r*Math.cos(theta);
       var y = k - r*Math.sin(theta);  
       ctx.lineTo(x,y);
     }

    ctx.closePath();     //close the end to the start point
ctx.stroke();        //actually draw the accumulated lines
}
</script>

</body>
</html>

No comments: