xxxxxxxxxx
50
// Global variable for a graphcis object to act like a layer
let gLayer;
function setup() {
createCanvas(400, 400);
// Create the graphics object with the same size as the canvas.
gLayer = createGraphics(width, height);
// We can se the color mode and other graphics properties on the canvas...
strokeWeight(10);
colorMode(RGB);
fill(255, 255, 0);
// ...but they WON'T affect the graphics object. If we want to change
// the graphic properties of that, we need to set them differently.
// This is good because it lets you have different properties in each layer.
gLayer.colorMode(HSB);
gLayer.noStroke();
gLayer.fill(120, 100, 100, 0.5);
}
function draw() {
background(220);
// Draw a smiley face each frame
circle(200, 200, 150);
circle(150, 200, 10);
circle(250, 200, 10);
line(160, 220, 240, 220);
// If the mouse is pressed, draw a spray effect into the graphics object
if (mouseIsPressed){
// Draw 10 randomly placed dots.
for (let i = 0; i < 10; i++){
// You can use the normal drawing functions, just add the name of the
// variable 'gLayer' in front with a 'dot' before the function name.
// Note that this does not draw into the main canvas but into a separate layer.
let x = mouseX + random(-10, 10);
let y = mouseY + random(-10, 10);
let d = random(2, 10);
gLayer.circle(x, y, d);
}
}
// Finally, we need to display the graphics layer using the image function.
// If you don't do this, the layer won't be visible.
image(gLayer, 0, 0);
}