Sets the p5.Shader object to apply while drawing.
Shaders are programs that run on the graphics processing unit (GPU). They can process many pixels or vertices at the same time, making them fast for many graphics tasks.
You can make new shaders using p5.strands with the buildMaterialShader, buildColorShader, and buildNormalShader functions. You can also use buildFilterShader alongside filter, and buildStrokeShader alongside stroke.
The parameter, s, is the p5.Shader object to apply. For example, calling shader(myShader) applies myShader to process each pixel on the canvas. This only changes the fill (the inner part of shapes), but does not affect the outlines (strokes) or any images drawn using the image() function. The source code from a p5.Shader object's fragment and vertex shaders will be compiled the first time it's passed to shader().
Calling resetShader() restores a sketch’s default shaders.
Note: Shaders can only be used in WebGL mode.
For advanced usage, shaders can be written in a language called GLSL. p5.Shader objects can be created in this way using the createShader() and loadShader() functions.
let fillShader;
let vertSrc = `
precision highp float;
attribute vec3 aPosition;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
varying vec3 vPosition;
void main() {
vPosition = aPosition;
gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aPosition, 1.0);
}
`;
let fragSrc = `
precision highp float;
uniform vec3 uLightDir;
varying vec3 vPosition;
void main() {
vec3 lightDir = normalize(uLightDir);
float brightness = dot(lightDir, normalize(vPosition));
brightness = clamp(brightness, 0.4, 1.0);
vec3 color = vec3(0.3, 0.5, 1.0);
color = color * brightness * 3.0;
gl_FragColor = vec4(color, 1.0);
}
`;
function setup() {
createCanvas(200, 200, WEBGL);
fillShader = createShader(vertSrc, fragSrc);
noStroke();
describe('A rotating torus with simulated directional lighting.');
}
function draw() {
background(20, 20, 40);
let lightDir = [0.5, 0.5, 1.0];
fillShader.setUniform('uLightDir', lightDir);
shader(fillShader);
rotateY(frameCount * 0.02);
rotateX(frameCount * 0.02);
torus(25, 10, 30, 30);
}If you want to apply shaders to strokes or images, use the following methods:
- strokeShader() : Applies a shader to the stroke (outline) of shapes, allowing independent control over the stroke rendering using shaders.
- imageShader() : Applies a shader to images or textures, controlling how the shader modifies their appearance during rendering.
Examples
Syntax
shader(s)
Parameters
Related References
copyToContext
Copies the shader from one drawing context to another.
inspectHooks
Logs the hooks available in this shader, and their current implementation.
modify
Returns a new shader, based on the original, but with custom snippets of shader code replacing default behaviour.
setUniform
Sets the shader’s uniform (global) variables.