Intro to Pts.js: Code a flashing square
Date: 2023-08-09 | create | tech | typescript | javascript | ptsjs |
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?
Answer
For this example, we'll be drawing a square to the middle of our canvas and making it cycle between two states each second:
- White with a black outline
- Solid red
Solution Overview
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
- Create a rectangle in the middle of the page
- Each second - increment a
colorCounter
- if colorCounter is even -> color red
- else -> color white with black borders
Specific Concepts
- Tempo - Provides a hook to execute something on a tempo (beats per minute). This is a fascinating approach to animation / synchronization pulled from audio / music land. You essentially create a time-based hook (via tempo) that you can then have execute arbitrary code on each "beat". We'll use this to increment a counter to tell us what "state" our square is in and thus what color it should be.
- More on Tempo in the official Pts Animation guide
- Rectangle.from(...) - Everything in Pts is a... Pt. So to create higher-ordered shapes (e.g. square, circle, etc) we actually create the pts that define them. Pts provides many helper functions to make creating these Pts a bit easier and Rectangle is one of those, creating the Pts that define this rectangle based on your inputs.
- More on creating shapes in the official Pts Op guide
- Fill / Stroke - Once you have a Pt / Group of Pts you can draw them to your Space. We use this
Code
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)
)
}
});
})();
Want more like this?
The best / easiest way to support my work is by subscribing for future updates and sharing with your network.