Clock

A clock

Source Code for this Sketch

const randStep = 1
const clockStep = 1
const hueStep = 5

let hours
let minutes
let seconds

// radialpoint returns [x, y] coordinates at the
// edge of circle with radius r, at angle deg
// along the edge, with 0 degrees being north
function radialpoint(r, deg) {
	let x = cos(deg-90)*r
	let y = sin(deg-90)*r

	return [x, y]
}

class Hand {
	constructor(r, deg, weight) {
		this.r = r
		this.weight = weight

		let xy = radialpoint(r, deg)
		this.x = xy[0]
		this.y = xy[1]

		this.hue = random(0, 360)
	}

	draw(deg) {
		let xy = radialpoint(this.r, deg)
		let targetX = xy[0]
		let targetY = xy[1]

		this.hue += random(-hueStep, hueStep)
		if (this.hue > 360) {
			this.hue -= 360
		}
		if (this.hue < 0) {
			this.hue = 360-this.hue
		}

		let x = this.x + random(-randStep, randStep)
		let y = this.y + random(-randStep, randStep)

		if (targetX > x) {
			x += clockStep
		}
		if (targetX < x) {
			x -= clockStep
		}
		if (targetY > y) {
			y += clockStep
		}
		if (targetY < y) {
			y -= clockStep
		}

		strokeWeight(this.weight)
		stroke(this.hue, 100, 50)
		line(x, y, this.x, this.y)
		line(0, 0, x, y)

		this.x = x
		this.y = y
	}
}

function wipe(deg) {
	let xy = radialpoint(170, deg-10)

	strokeWeight(2)
	stroke(0, 0, 100)
	line(0, 0, xy[0], xy[1])
}

function currentMinutes() {
	return new Date(Date.now()).getMinutes() * 6
}

function currentSeconds() {
	return new Date(Date.now()).getSeconds() * 6
}

function currentMilliseconds() {
	return new Date(Date.now()).getMilliseconds() * 6 / 1000 + currentSeconds()
}

function currentHours() {
	let h = new Date(Date.now()).getHours()
	if(h > 12) {
		h-=12
	}
	return 180 - 360 * (h / 12)
}

function setup() {
	createCanvas(400, 400, P2D, canvas)
	colorMode(HSL)
	background(100)
	translate(width/2, height/2)
	strokeWeight(1)
	angleMode(DEGREES)

	hours = new Hand(50, currentHours(), 3)
	minutes = new Hand(100, currentMinutes(), 2)
	seconds = new Hand(150, currentSeconds(), 1)
}

function draw() {
	translate(width/2, height/2)

	strokeWeight(0)

	// Fade
	fill(0, 100, 100, .1)
	rect(-width/2, -height/2, width, height)

	// Clear the "burn-in" trail that fade doesn't clean up
	wipe(currentMilliseconds())

	// 12, 3, 6, 9 o'clock markers
	strokeWeight(1)
	stroke(0)
	line(0, 150, 0, 170)
	line(0, -150, 0, -170)
	line(-150, 0, -170, 0)
	line(150, 0, 170, 0)

	seconds.draw(currentSeconds())
	minutes.draw(currentMinutes())
	hours.draw(currentHours())

	// Center of the clock
	fill(0)
	stroke(0)
	strokeWeight(0)
	circle(0, 0, 6)
}

You may use all or part of the p5 code seen on this page for your own creations, without restriction. Attribution is appreciated but not required.

This sketch also includes the following sources: p5common.js . Sources are available under their respective licenses.

See all p5.js sketches