.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
sivanagamahesh

Home >> Code Snippets >> Javascript >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Using canvas: drawing stars with variable number of tips

Posted By:Kemal AL GAZZAH       Posted Date: November 11, 2015    Points: 40    Category: Javascript    URL: http://www.dotnetspark.com  

This is an illustration of canvas use to draw stars with a given number of tips.
 

This code draws a star with N tips and allows user to save the picture to a png file using the right-click button.
example:
20 tips
gap=9


<html>
<head>
<script language="javascript">
/*
darwing start with n tips
by Kamel Gazzah
kamelgazzah@gmail.com
11/11/2015
*/
function draw()
{

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.clearRect(0, 0, 1000, 1000);
var radius = 200;
var cx = c.width / 2;
var cy = c.height / 2;
ctx.beginPath();


ctx.lineWidth = 1;
ctx.strokeStyle = '#003300';
var theta=Math.PI/2;
var x = cx + radius  * Math.sin(theta);
var y = cy - radius  * Math.cos(theta);
var N = document.getElementById("txtn").value;

for(i=1;i<N+1;i++)
{
for(j=i+1*document.getElementById("txte").value;j<i+1*document.getElementById("txte").value+1;j++)
{
var theta=i*(2*Math.PI)/N;
var x = cx + radius  * Math.sin(theta);
var y = cy - radius  * Math.cos(theta);

var theta1=(j)*(2*Math.PI)/N;
var x1 = cx + radius  * Math.sin(theta1);
var y1 = cy - radius  * Math.cos(theta1);

ctx.moveTo(x,y);
ctx.lineTo(x1,y1);

}
}
ctx.closePath();
ctx.lineWidth = 2;
ctx.strokeStyle = 'red';
ctx.stroke();
var dataURL = c.toDataURL();
document.getElementById('canvasimg').src = dataURL;
}


</script>
</head>
<body>

<table>
<tr>
<td>Tips number</td>
<td><input type="text" id="txtn" value=5 /></td>
<td>Number of Gaps between two tips</td>
<td><input type="text" id="txte" value=3 /></td>
<td><input type="button" value="Validate" onClick="draw()" /></td>
</tr>
</table>
<canvas id="myCanvas" width="500" height="500"  style="display:none;">Your browser does not support the HTML5 canvas tag.</canvas>
<img id="canvasimg" alt="right click to save"/>
<script>
draw()
</script>
</body>
</html>


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend