Pointer, time and resolution
Feed the pointer, the time and the canvas size into a fragment shader, in units the shader can use directly.
Most full-screen shaders want the same three inputs: where the pointer is, how much time has passed, and how big the canvas is. Each arrives as a uniform. The work is in the units. A fragment shader knows where it is through gl_FragCoord, in device pixels from the bottom left, while a pointer event gives CSS pixels from the top left of the page. Convert the pointer once, in JavaScript, to match gl_FragCoord, and the shader can compare the two directly.
import { Renderer, Mesh, Program, Triangle, Uniform, Vec2 } from 'wtc-gl'
// A grid of dots that swell towards the pointer. The pointer, time and
// resolution reach the shader as uniforms, all in device pixels.
const vertex = /* glsl */ `#version 300 es
in vec2 position;
void main() {
gl_Position = vec4(position, 0.0, 1.0);
}`
const fragment = /* glsl */ `#version 300 es
precision highp float;
uniform vec2 u_resolution; // the canvas, in device pixels
uniform vec2 u_pointer; // smoothed, in device pixels, y up
uniform float u_hover; // 0 to 1, eased in and out
uniform float u_time;
out vec4 colour;
void main() {
// Centred, aspect-correct: y from -0.5 to 0.5, x as wide as it needs
vec2 p = (gl_FragCoord.xy - 0.5 * u_resolution) / u_resolution.y;
vec2 m = (u_pointer - 0.5 * u_resolution) / u_resolution.y;
vec2 cell = p * 22.0;
vec2 centre = (floor(cell) + 0.5) / 22.0;
float d = length(centre - m);
float glow = exp(-d * 6.0) * u_hover;
float pulse = 0.5 + 0.5 * sin(u_time * 4.0 - d * 30.0);
float r = 0.1 + 0.3 * glow * (0.7 + 0.3 * pulse);
float disc = 1.0 - smoothstep(r - 0.05, r + 0.05, length(fract(cell) - 0.5));
vec3 tint = mix(vec3(0.29, 0.62, 1.0), vec3(0.95, 0.42, 0.26), glow);
float alpha = disc * (0.35 + 0.65 * glow);
colour = vec4(tint * alpha, alpha); // premultiplied
}`
export default function (container) {
const renderer = new Renderer({
dpr: Math.min(devicePixelRatio, 2),
alpha: true,
premultipliedAlpha: true,
clearColour: [0, 0, 0, 0]
})
const { gl } = renderer
const canvas = gl.canvas
container.appendChild(canvas)
const u_resolution = new Uniform({
name: 'resolution',
value: [1, 1],
kind: 'float_vec2'
})
const u_pointer = new Uniform({
name: 'pointer',
value: [0, 0],
kind: 'float_vec2'
})
const u_hover = new Uniform({ name: 'hover', value: 0, kind: 'float' })
const u_time = new Uniform({ name: 'time', value: 0, kind: 'float' })
const mesh = new Mesh(gl, {
geometry: new Triangle(gl),
program: new Program(gl, {
vertex,
fragment,
uniforms: { u_resolution, u_pointer, u_hover, u_time }
})
})
// Where the pointer is, in device pixels with y up, like gl_FragCoord
const target = [0, 0]
let inside = false
const onMove = (e) => {
const rect = canvas.getBoundingClientRect()
target[0] = (e.clientX - rect.left) * (canvas.width / rect.width)
target[1] = (rect.bottom - e.clientY) * (canvas.height / rect.height)
inside = true
}
const onLeave = () => (inside = false)
canvas.addEventListener('pointermove', onMove)
canvas.addEventListener('pointerdown', onMove)
canvas.addEventListener('pointerleave', onLeave)
return {
frame(time, delta) {
// Ease towards the target, the same amount per second at any frame rate
const follow = 1 - Math.exp(-delta * 10)
const p = u_pointer.value
p[0] += (target[0] - p[0]) * follow
p[1] += (target[1] - p[1]) * follow
u_hover.value +=
((inside ? 1 : 0) - u_hover.value) * (1 - Math.exp(-delta * 4))
u_time.value = time
renderer.render({ scene: mesh })
},
resize(width, height) {
renderer.dimensions = new Vec2(width, height)
u_resolution.value = [canvas.width, canvas.height]
if (!inside) {
target[0] = canvas.width / 2
target[1] = canvas.height / 2
}
},
dispose() {
canvas.removeEventListener('pointermove', onMove)
canvas.removeEventListener('pointerdown', onMove)
canvas.removeEventListener('pointerleave', onLeave)
mesh.geometry.remove()
mesh.program.remove()
renderer.dispose()
canvas.remove()
}
}
}Resolution
Set the resolution to the canvas's drawing buffer, gl.canvas.width and gl.canvas.height. These are in device pixels, the CSS size times the renderer's dpr, the same units as gl_FragCoord:
resize(width, height) {
renderer.dimensions = new Vec2(width, height)
u_resolution.value = [gl.canvas.width, gl.canvas.height]
}In the shader, divide by the height to get coordinates that are the same scale both ways, centred on the middle of the canvas:
vec2 p = (gl_FragCoord.xy - 0.5 * u_resolution) / u_resolution.y;p.y runs from -0.5 to 0.5, and p.x as far as the aspect ratio takes it. A circle drawn with length(p) stays round however the canvas is shaped. Dividing by u_resolution instead gives 0 to 1 both ways, which suits reading a texture but stretches shapes.
Pointer
Listen on the canvas, and convert the event to the canvas's device pixels, with y up:
const canvas = gl.canvas
const onMove = (e) => {
const rect = canvas.getBoundingClientRect()
target[0] = (e.clientX - rect.left) * (canvas.width / rect.width)
target[1] = (rect.bottom - e.clientY) * (canvas.height / rect.height)
}
canvas.addEventListener('pointermove', onMove)Scaling by canvas.width / rect.width rather than devicePixelRatio matters. The renderer caps its dpr (at 2, in these examples), so on a 3× phone the two disagree, and the pointer lands in the wrong place. The ratio also stays right if CSS stretches the canvas.
Then convert the pointer in the shader the same way as gl_FragCoord, so both are in the same space:
vec2 m = (u_pointer - 0.5 * u_resolution) / u_resolution.y;
float d = length(p - m); // distance to the pointer, in canvas heightsPointer events cover the mouse, pens and touch alike. A touch only moves while the finger is down, so listen for pointerdown too, so that a tap moves the target. On touch screens, dragging over the canvas scrolls the page and cancels the pointer. Set touch-action: none on the canvas if the shader should follow a dragging finger instead, at the cost of the page not scrolling from there.
Remove the listeners when you're done with the canvas:
canvas.removeEventListener('pointermove', onMove)Smoothing
Moving the uniform straight to the pointer looks twitchy. Ease it towards the target every frame instead. With a fixed fraction per frame, the easing depends on the frame rate, so work out the fraction from the frame's length:
frame(time, delta) {
const follow = 1 - Math.exp(-delta * 10)
const p = u_pointer.value
p[0] += (target[0] - p[0]) * follow
p[1] += (target[1] - p[1]) * follow
}Larger numbers than 10 follow more tightly. Changing the uniform's array in place is fine: a uniform compares its values, not the array, to decide whether to upload.
The same easing works for anything that should fade in and out. The example eases u_hover towards 1 while the pointer is over the canvas, and back to 0 on pointerleave, so the effect doesn't snap off when the pointer leaves.
Time
Give the shader the time in seconds, as a float:
u_time.value = timeA float has about seven significant figures, so after a day or so of running, sin(u_time * 40.0) starts to step. For a page that might stay open, wrap the time on a period that suits the animation, such as time % 3600, or keep the phases in JavaScript.
FragmentShader makes u_time and u_resolution for you. Its u_time doesn't count seconds: it grows by a fraction of each frame's length, so scale it in the shader to taste. Add a pointer uniform of your own through its uniforms option.
See also
- Your first shader, for the full-screen triangle and the program
- Uniforms, for uniform kinds and how values are compared
- Feedback with ping-pong buffers, to paint with the pointer
- Pick and drag, for the pointer in a 3D scene
- API: Uniform, Renderer, FragmentShader