Welcome :Guest

Congratulations!!!

Top 5 Contributors of the Month
Pankaj Mishra
Shivakumaran
alex morco
Imran Ghani
Meenakshi

 Home >> Code Snippets >> Javascript >> Post New Resource

# 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>
<script language="javascript">
/*
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 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>
<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>```

Responses

No response found. Be the first to respond this post

Post Comment