The concept
A spatial anchor attaches a virtual object to a real-world point. Even as the camera moves, the object stays in place. In AR, the world→camera transform is computed each frame. In p5.js, we simulate by keeping a fixed position and applying an offset based on simulated camera movement.
The code
// Spatial anchor simulation: object stays fixed as 'camera' moves
let anchorX = 200, anchorY = 140; // fixed world position
let camX = 0, camY = 0;
function setup() { createCanvas(400, 280); }
function draw() {
background(11, 15, 20);
// Camera follows mouse slowly (simulating head movement)
camX = lerp(camX, mouseX - width/2, 0.05);
camY = lerp(camY, mouseY - height/2, 0.05);
// World origin indicator
stroke(60,70,90,80); strokeWeight(1);
line(0, height/2, width, height/2);
line(width/2, 0, width/2, height);
// Anchored object: screen pos = world pos - camera offset
let sx = anchorX - camX, sy = anchorY - camY;
noStroke(); fill(55, 227, 195);
ellipse(sx, sy, 28, 28);
fill(255,255,255,120); textAlign(CENTER);
text('anchor', sx, sy + 24);
}Going further
Explore other free courses on the Workshops page.
Practice, collaborate, deploy — in 15 min.
Book a discovery call →