xxxxxxxxxx
158
class Circle
{
constructor(x, y, radius)
{
this.x = x;
this.y = y;
this.radius = radius;
}
}
const TargetMeasure = Object.freeze(
{
Radius: 0, Diameter: 1, Circumference: 2, Area: 3, COUNT: 4,
});
let circles = []; // array of circles to be drawn as they are created
let center = null; // center of the preview circle
let pulseTimer = 0;
let pulsePeriod = 2.37;
let growthRate = 50;
let currentRadius = 0;
let currentTarget;
function setup()
{
createCanvas(400, 400);
textAlign(CENTER, CENTER);
textSize(16);
textStyle(BOLD);
ChooseRandomTarget();
}
function DrawCircle(c)
{
strokeWeight(2);
stroke(20, 100, 250, 255);
fill(20, 100, 250, 100);
circle(c.x, c.y, c.radius * 2);
}
function PreviewCircle(c)
{
let inner = 2 * PI * pulseTimer / pulsePeriod;
let interpolant = (1 - cos(inner)) / 2;
let from = color(20, 100, 250, 50);
let to = color('white');
let previewColor = lerpColor(from, to, interpolant);
// draw the circle
strokeWeight(1);
stroke(previewColor);
noFill();
circle(c.x, c.y, c.radius * 2);
let targetValue;
let targetName;
switch (currentTarget)
{
default: // TargetMeasure.Radius
targetValue = c.radius;
targetName = "Radius";
break;
case TargetMeasure.Diameter:
targetValue = 2 * c.radius;
targetName = "Diameter";
break;
case TargetMeasure.Circumference:
targetValue = 2 * PI * c.radius;
targetName = "Circumference";
break;
case TargetMeasure.Area:
targetValue = PI * c.radius * c.radius;
targetName = "Area";
break;
}
// prepare the text
let circleText = round(targetValue, 1).toLocaleString(
undefined, {minimumFractionDigits: 1});
// draw the text's shadow and then the text itself
strokeWeight(2);
stroke(0, 0, 0, 255);
fill(0, 0, 0, 255);
text(targetName, c.x + 1, c.y + 1 - 8 - 10);
text(circleText, c.x + 1, c.y + 1 + 7 - 10);
fill(255, 255, 255, 255);
text(targetName, c.x, c.y - 8 - 10)
text(circleText, c.x, c.y + 7 - 10);
pulseTimer += dt();
pulseTimer %= pulsePeriod;
}
function DrawAllCircles()
{
for (let i = 0; i < circles.length; ++i)
{
DrawCircle(circles[i]);
}
}
function ClearCircles()
{
circles = [];
}
function keyPressed()
{
if (keyCode === 32) // spacebar
{
ClearCircles();
}
}
function draw()
{
background(20, 30, 40);
if (mouseIsPressed)
{
if (mouseButton === LEFT)
{
if (center === null)
{
center = createVector(mouseX, mouseY);
currentRadius = 0;
}
currentRadius += growthRate * dt();
}
}
else
{
if (center !== null)
{
circles.push(new Circle(center.x, center.y, currentRadius));
center = null;
}
}
DrawAllCircles();
if (center !== null)
{
let c = new Circle(center.x, center.y, currentRadius);
PreviewCircle(c);
}
}
function ChooseRandomTarget()
{
currentTarget = int(Math.random() * TargetMeasure.COUNT);
}
function dt() { return deltaTime / 1000; }