javascriptp5.jspixel-density

How can I change pixelDensity midway through running the sketch?


I'm trying to change the sketch's pixel density after its been first initialized in setup. Basically, user can interact with some UI inputs and it should change pixelDensity based on that. However I haven't found way to actually change the pixelDensity other than the one instance in setup(). Is it even possible?

This is a simplified version of my code. There is an event handler that calls updateSettings() on input event on the input element.

let pd = 2

setup() {
  createCanvas(windowWidth, windowHeight)
  pixelDensity(pd)
}

// EDIT: Adding missing code for more context
let settingsList = {
   panel: document.querySelector(".settings"),
   closeIcon: document.querySelector(".settings-exit"),
   settingInputs: [
      document.querySelector(".settings input[name='pixelDensity']")   
   ]
}

settingsList.settingInputs.forEach((input) => {
  input.addEventListener("input", (e) => {
      updateSettings(e.target)
   })
})

function updateSettings(target) {
  if (target.name == "pixelDensity" && pd != target.value) {
    pd = target.value
    changePixelDensity()
  }
}

function changePixelDensity() {
  pixelDensity(pd)
}

What I'm trying to do is let user change the pixel count of the sketch to hopefully lower the impact on CPU, then after everything is generated, user can put back the pixel density to draw the sketch in full detail.


Solution

  • I think you've simplified the code too much. There's not enough context to run the code and reproduce the problem.

    The issue may be that you're not converting target.value from a string to a number, though. Try +target.value.

    Here's a working example:

    function setup() {
      createCanvas(windowWidth, windowHeight);
      pixelDensity(1);
      drawCircle();
    }
    
    function drawCircle() {
      background(200);
      circle(50, 50, 70);
    }
    
    function changePixelDensity({target}) {
      pixelDensity(+target.value);
      drawCircle();
    }
    
    document
      .querySelector("input")
      .addEventListener("change", changePixelDensity);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.9.0/p5.js"></script>
    <input type="range" min="0.1" max="10" value="0.5" step="0.1">

    It could also be that target.name is not "pixelDensity" as you think it is. When a condition isn't running, add a print above it to examine the variables used in the condition, as well as their types (print(typeof someVar, someVar)) to make sure they're as you expect.