Separating effects

This is a snippet from my main code. I have two separate ellipses. I only want the central ellipse to have a shadowing effect. How do I limit the shadowing effect specifically to the central ellipse, and not to the smaller ellipse in the lower left?

function setup() {
  createCanvas(400, 400);
  background(255);
}

function draw() {

  // lower left ellipse
    noStroke();
    fill(255,50,0);
   ellipse(50, 375, 25, 25);
  

//shadow effect
  drawingContext.shadowOffsetX = -2;
  drawingContext.shadowOffsetY = 3;
  drawingContext.shadowBlur = 1;
  drawingContext.shadowColor = 'black'; 

// central ellipse (main) 
  let c = color(130, 130, 0);                 //COLOR = ATOMIC MASS
  fill(c);
  noStroke();
  ellipse(200, 200, 150, 150);
  
 
}
2 Likes

Hi @achip30,

Welcome to the forum! :wink:

In order to save and restore the context, you can use the CanvasRenderingContext2D methods: save() and restore()

They work just like push() and pop():

drawingContext.save(); // Save the current style

drawingContext.shadowOffsetX = -2;
drawingContext.shadowOffsetY = 3;
drawingContext.shadowBlur = 1;
drawingContext.shadowColor = 'black'; 
  
fill(130, 130, 0);
noStroke();
ellipse(200, 200, 150, 150);
  
drawingContext.restore(); // Restore the style
3 Likes

Thank you so much! New to p5 and I figured it was something simple lol.

2 Likes

Hello, @achip30, and welcome to the Processing Forum!

It is important to remember that draw() is called repeatedly, unless you specify otherwise.

See p5.js Reference: draw().

The following, which is a modified version of your code, may help you observe what happened:

function setup() {
  createCanvas(200, 200);
  background(255);
  frameRate(0.5);
  noStroke();
  textSize(20);
}

function draw() {
  background(255);
  text("Frame " + frameCount, width / 2, height - 25);
  fill(255,50,0);
  
  // smaller ellipse in the lower left
  ellipse(50, height - 25, 25, 25);
  
  // invoke shadowing
  drawingContext.shadowOffsetX = -8;
  drawingContext.shadowOffsetY = 8;
  drawingContext.shadowBlur = 1;
  drawingContext.shadowColor = 'blue'; 
  let c = color(130, 130, 0); //COLOR = ATOMIC MASS
  fill(c);
  
  // central ellipse
  ellipse(width / 2, height / 2, width / 3, height / 3);
}

Below are renderings of the sketch during the first two frames:
frame1

frame2

During frame 1, the smaller ellipse in the lower left and the text were drawn before shadowing was in effect. The central ellipse was drawn after shadowing had been activated.

Since you did not specify otherwise, shadowing was still in effect at the start of frame 2, and throughout the duration of every frame thereafter.

3 Likes

Great explanation. This actually got me to read about noLoop(), which helped solve another problem I was having. Thank you!

3 Likes

Ahh love it, this is what everyone should do! Reading the docs is underrated :stuck_out_tongue_winking_eye:

1 Like