aframe-sprite-component icon indicating copy to clipboard operation
aframe-sprite-component copied to clipboard

ideas for efficient image loading

Open micuat opened this issue 4 years ago • 2 comments

This is not an issue but rather a feature request - currently the component loads the texture every time when <a-sprite> is processed, right? I made a workaround to reuse same textures:

var textureSingleton = {};

AFRAME.registerComponent('sprite', {

  schema: {
    src: {
      default: ''
    },
    resize: {
      default: '1 1 1'
    }
  },


  init: function () {
    this.textureLoader = new THREE.TextureLoader();
  },


  play: function () {
    if (textureSingleton[this.data.src] == undefined) {
      textureSingleton[this.data.src] = this.textureLoader.load(this.data.src);
    }
    this.map = textureSingleton[this.data.src];

    this.material = new THREE.SpriteMaterial({
      map: this.map
    });

    this.sprite = new THREE.Sprite(this.material);

    resizeData = this.data.resize.split(' ');
    this.sprite.scale.set(resizeData[0], resizeData[1], resizeData[2]);

    this.el.setObject3D('mesh', this.sprite);
  },


  remove: function () {
    console.log('remove sprite');
    if (this.mesh) this.el.removeObject3D('mesh');
  }

});

AFRAME.registerPrimitive('a-sprite', {
  defaultComponents: {
    sprite: {}
  },
  mappings: {
    src: 'sprite.src',
    resize: 'sprite.resize'
  }
});

And perhaps a better way is to use <a-assets><img> as a source. A friend of mine showed me an example to load <img> into three.js texture (this uses data URL but you can think of reading from static <img> - this example might suppress multiple http requests but still creates multiple textures, I guess) : https://codepen.io/fand/pen/LYpJMqW

micuat avatar May 15 '20 09:05 micuat