p5.js icon indicating copy to clipboard operation
p5.js copied to clipboard

[p5.js 2.0+ Bug Report]: set() with p5.Image/p5.Graphics leaks drawing context state

Open bhabishnu opened this issue 2 months ago • 2 comments

Most appropriate sub-area of p5.js?

  • [ ] Accessibility
  • [ ] Color
  • [x] Core/Environment/Rendering
  • [ ] Data
  • [ ] DOM
  • [ ] Events
  • [ ] Image
  • [ ] IO
  • [ ] Math
  • [ ] Typography
  • [ ] Utilities
  • [ ] WebGL
  • [ ] WebGPU
  • [ ] p5.strands
  • [ ] Build process
  • [ ] Unit testing
  • [ ] Internationalization
  • [ ] Friendly errors
  • [ ] Other (specify if possible)

p5.js version

2.3.2 and current main. Does not reproduce on 2.1.2.

Web browser and version

Chrome 152.0.7977.64

Operating system

Fedora Linux

Steps to reproduce this

function setup() {
  createCanvas(120, 120);

  const img = createImage(1, 1);
  // Also reproduces with:
  // const img = createGraphics(1, 1);

  push();
  translate(50, 50);

  console.log('before set', drawingContext.getTransform());

  set(90, 90, img);

  console.log('after set', drawingContext.getTransform());

  pop();

  console.log('after pop', drawingContext.getTransform());

  noStroke();
  fill('blue');
  rect(0, 0, 20, 20);
}

Expected behavior

set() should preserve the drawing context state.

After set(), the transform should still be translated by (50, 50), and after pop() it should return to identity. The final rectangle should be drawn at the top-left.

Actual behavior

On 2.3.2 and current main:

  • before set() → translated (50, 50)
  • after set() → identity
  • after pop() → translated (50, 50)

The final rectangle is drawn around (50, 50) instead of the top-left.

This reproduces with both p5.Image and p5.Graphics.

Additional context

Renderer2D.set() calls drawingContext.save() for the p5.Image / p5.Graphics path but currently has no matching restore().

In v2.1.2, the corresponding path had a matching restore(). This appears to have been introduced in commit 5cba0fa1a, where the Image and Graphics branches were combined. The first stable release I could reproduce it on is v2.2.0.

bhabishnu avatar Sep 26 '26 06:09 bhabishnu

good catch, are you interested in making a fix + adding a unit test to prevent regressions?

davepagurek avatar Sep 26 '26 14:09 davepagurek

Yep, happy to! I’ll work on the fix + regression test and open a PR once it’s ready.

bhabishnu avatar Sep 26 '26 15:09 bhabishnu