HTML File
<head>
<script src="nine.js"></script>
</head>
<canvas id="polygons" width="400" height="400" style="border:1px solid #000000;"></canvas>
<script>
let canvas = document.getElementById("polygons");
let ctx = canvas.getContext('2d');
let cx = canvas.width/2;
let cy = canvas.height/2;
let shapes = [];
let r = 10;
for(let sides =3; sides < 20; sides ++) {
shapes.push(new Shape(sides, r));
r += 10;
}
for(let i=0; i<shapes.length;i++) {
shapes[i].RandomColor();
}
for (let i=0; i < shapes.length; i++) {
shapes[i].Display(ctx, cx, cy);
}
</script>
"use strict"
function RandInt(scale) {
return Math.floor(Math.random()*scale);
}
class Point{
y = 0;
constructor(xval, yval) {
if (xval != undefined) {
this.x = xval;
} else {
this.x = 0;
}
if (yval != undefined) {
this.y = yval;
}
}
get gety() {
console.log("In the yval getter");
return this.y;
}
set sety(val) {
console.log("in the y val setter");
if (val < 10 && val > -10) {
this.y = val;
} else {
console.log("Point Y value is restricted to single digits");
}
}
Move(ctx, cx, cy){
ctx.moveTo(this.x+cx, this.y+cy);
}
Line(ctx, cx, cy){
ctx.lineTo(this.x+cx, this.y+cy);
}
StringVal() {
return "(" + this.x + ", " + this.y + ")";
}
}
function PointDemo() {
let p1 = new Point();
let p2 = new Point(3,5);
console.log(p1.StringVal());
console.log(p2.StringVal());
p1.x = 5;
p1.y = 9;
console.log(p1.StringVal());
// using direct access to x and a getter for y.
console.log("The point x = ", p1.x, " and y = ", p1.gety);
// using a setter for y
p1.sety= 99;
console.log(p1.StringVal());
}
class Shape {
points = [];
color = "black";
constructor (size=3, radius=10) {
let angle = 2*Math.PI/size;
let theta = 0;
let xCord,yCord;
for(let i=0;i<=size;i++) {
xCord = radius * Math.cos(theta);
yCord = radius * Math.sin(theta);
this.points.push(new Point(xCord,yCord));
theta+= angle;
}
this.color = "black";
}
set SetColor(color) {
this.color = color;
}
get GetColor(){
return this.color;
}
RandomColor() {
this.color = "rgb("+ RandInt(255) + ","
+ RandInt(255) +","
+ RandInt(255) + ")";
}
Display(ctx, cx, cy) {
ctx.strokeStyle = this.color;
ctx.beginPath();
this.points[0].Move(ctx, cx, cy);
for (let i=1; i < this.points.length; i++) {
this.points[i].Line(ctx,cx, cy);
}
ctx.stroke();
}
}