HTML5 Game - Canvas Shape Star

Draw Star inside a circle

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="1000" height="850" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>
'use strict'//w  ww.ja v  a2 s  .  co  m
let c = document.getElementById("myCanvas");
let ctx = c.getContext("2d");

ctx.beginPath();
//ctx.lineWidth = "6";
//ctx.strokeStyle = "red";

let x = 300;
let y = 300;
let width = 300;
let height = 300;
let radius = 200;
let num_sections = 5; //set this for number of divisions

drawCircle(ctx, x,y,radius)
ctx.stroke();

let points = [];

for (let i = 1; i <= num_sections; i++) {
 // drawAngledLine(x, y, radius, i * (360 / num_sections));
  let point = getPointOnCircle(x, y, radius, i * (360 / num_sections));
  points.push(point);
}

drawLine(ctx, '2', points[0].x,points[0].y,points[2].x,points[2].y);
drawLine(ctx, '2', points[0].x,points[0].y,points[3].x,points[3].y);
drawLine(ctx, '2', points[1].x,points[1].y,points[3].x,points[3].y);
drawLine(ctx, '2', points[1].x,points[1].y,points[4].x,points[4].y);
drawLine(ctx, '2', points[2].x,points[2].y,points[4].x,points[4].y);

for (let i = 1; i <= num_sections; i++) {
 // drawAngledLine(x, y, radius, i * (360 / num_sections));
  let point = getPointOnCircle(x, y, radius, i * (360 / num_sections));
  //drawCircle(ctx, point.x,point.y,5)
}


function degreeToRadian(degree){
   return degree / 180 * Math.PI;
}

function getEvenPointOnCircle(x, y, length, angle){
   
}
function getPointOnCircle(x, y, length, angle){
  let radians = degreeToRadian(angle);
  let endX = x + length * Math.cos(radians);
  let endY = y - length * Math.sin(radians);
  return {x:endX, y:endY};
}

function drawAngledLine(x, y, length, angle) {
   ctx.save();
  let radians = degreeToRadian(angle);
 let endX = x + length * Math.cos(radians);
  let endY = y - length * Math.sin(radians);
  ctx.beginPath();
  ctx.moveTo(x, y)
  ctx.lineTo(endX, endY);
  ctx.closePath();
  ctx.stroke();
  ctx.restore();
}
function drawLine(ctx, lineWidth, x0,y0,x1,y1){
  ctx.save();
  ctx.lineCap = "square";
  
  ctx.lineWidth = lineWidth;
       ctx.beginPath();
   ctx.moveTo(x0, y0 );
   ctx.lineTo(x1,y1);
       ctx.closePath();
   ctx.stroke();
   ctx.restore();
}

function drawCircle(ctx, x0,y0,radius){
    ctx.save();
     ctx.beginPath();
   ctx.arc(x0,y0, radius, 0, 2 * Math.PI, false);
    ctx.closePath();
   ctx.stroke();
   ctx.restore();
}
</script>

</body>
</html>

Related Topics