Essay - Published: 2023.08.09 | create | javascript | ptsjs | tech | typescript |
DISCLOSURE: If you buy through affiliate links, I may earn a small commission. (disclosures)
I've been exploring Pts for simple, declarative Typescript visualizations in web browsers for projects like TimeTick.
TimeTick is a memento mori esque visualization of time passing. So I wanted to have a flashing element every second to mimic a clock's second hand / represent the passing of time.
In this post we'll be exploring how to add time-based dynamism into Pts sketches, in particular:
Q: How to code a time-based flashing square in Pts?
For this example, we'll be drawing a square to the middle of our canvas and making it cycle between two states each second:
You can find the full code below but I wanted to highlight a few concepts that I think will make grokking the code a bit easier.
Solution Overview
colorCounterSpecific Concepts
I've copied and pasted the code I used to run this example below. I would recommend copying it into the Pts code playground and playing around with edits to further explore how it works.
/*
* Draws a flashing square to the canvas
*/
(function() {
console.log("Running")
// Pts quick start mode.
var run = Pts.quickStart( "#pt", "#fff" );
const rectangleSize = 25
let oneSecondTempo = new Tempo(60)
let colorCounter = 0
oneSecondTempo.every(1).start((count) => {
colorCounter = count
})
space.add(oneSecondTempo)
run( (time, ftime) => {
const rectangle = Rectangle.from(
space.center,
rectangleSize
)
if(colorCounter % 2 === 0) {
form
.stroke("#A71930 ")
.fill("#A71930 ")
.polygon(
Rectangle.corners(rectangle)
)
} else {
form
.stroke("#000")
.fill("#fff")
.polygon(
Rectangle.corners(rectangle)
)
}
});
})();
The best way to support my work is to like / comment / share for the algorithm and subscribe for future updates.