Skip to content

Implementation of loadBytes #2674

@shiffman

Description

@shiffman

I am opening a new issue since #40 about file i/o is a long thread and this relates specifically to loadBytes(). I am working on an example that loads binary data and thought I would take a crack at adding loadBytes() to p5. I have something working and am happy to pull request an implementation, however, I have a couple questions I'd love thoughts or advice on:

The working new method is towards the bottom.

  1. As discussed in Example of async function for callback and preload() on the libraries wiki, it's required that an original object pointer is retained. I've done this by placing the Uint8Array into a values property of a blank object. Thoughts on how this could be improved? Can I set the values of a Uint8Array if I don't know the size in advance?

  2. I think I am running into registerPreloadMethod mechanism is broken #2568 as I can only get this to work in 0.5.11 (no later versions).

p5.prototype.registerPreloadMethod('loadBytes');

function loadBytes(file, callback) {
  let data = {};
  let oReq = new XMLHttpRequest();
  oReq.open("GET", file, true);
  oReq.responseType = "arraybuffer";
  oReq.onload = function(oEvent) {
    let arrayBuffer = oReq.response;
    if (arrayBuffer) {
      data.values = new Uint8Array(arrayBuffer);
      if (callback) {
        callback(data);
      }
    }
  }
  oReq.send(null);
  return data;
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions