Skip to content

[p5.js 2.0 Bug Report]: [p5.js 2.0 Bug Report]: _onblur doesn't fully reset keyboard state , keyIsPressed and keyIsDown() stay stuck after losing focus #8540

@avinxshKD

Description

@avinxshKD

Most appropriate sub-area of p5.js?

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

p5.js version

2.x (main)

Web browser and version

Any

Operating system

Windows 11, but doesn't matter

Steps to reproduce this

Steps:

  1. Open a sketch with keyboard input (see snippet below)
  2. Click the canvas, then hold down the right arrow key
  3. While still holding it, Alt-Tab to another window
  4. Release the key in the other window
  5. Switch back to the sketch tab

Snippet:

function setup() {
  createCanvas(400, 200);
}

function draw() {
  background(220);
  textSize(16);
  text('keyIsPressed: ' + keyIsPressed, 20, 40);
  text('RIGHT_ARROW down: ' + keyIsDown(RIGHT_ARROW), 20, 80);
}

After step 5, both keyIsPressed and keyIsDown(RIGHT_ARROW) are still true even though no key is being held. The key stays "stuck" until you physically press and release it again inside the sketch. Super annoying in any movement-based sketch

Root cause:
_onblur in keyboard.js only clears _downKeys but completely ignores _downKeyCodes, keyIsPressed, key, and code:

// what's there now
fn._onblur = function(e) {
  this._downKeys = {};
};

_downKeyCodes is new to 2.x _onblur was just never updated when it got added. Since keyIsDown() checks both maps, clearing only one of them doesn't actually fix the stuck state.,

Fix would be:

fn._onblur = function(e) {
  this._downKeys = {};
  this._downKeyCodes = {};
  this.keyIsPressed = false;
  this.key = '';
  this.code = '';
};

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions