1
0
mirror of https://github.com/troisjs/trois.git synced 2024-11-24 12:22:03 +08:00
trois/src/meshes/Sprite.js

54 lines
1.3 KiB
JavaScript
Raw Normal View History

2020-09-19 18:16:16 +08:00
import { Sprite, SpriteMaterial, TextureLoader } from 'three';
2021-03-07 06:14:22 +08:00
import Object3D from '../core/Object3D.js';
2020-09-19 18:16:16 +08:00
export default {
2021-03-07 06:14:22 +08:00
extends: Object3D,
emits: ['loaded'],
2020-09-19 18:16:16 +08:00
props: {
src: String,
},
2021-03-07 06:14:22 +08:00
data() {
return {
loading: true,
};
2021-02-22 04:39:35 +08:00
},
2021-03-07 06:14:22 +08:00
created() {
2020-09-19 22:41:26 +08:00
this.texture = new TextureLoader().load(this.src, this.onLoaded);
2020-09-19 18:16:16 +08:00
this.material = new SpriteMaterial({ map: this.texture });
this.sprite = new Sprite(this.material);
2020-09-19 22:41:26 +08:00
this.geometry = this.sprite.geometry;
2021-03-07 06:14:22 +08:00
this.initObject3D(this.sprite);
2020-09-19 18:16:16 +08:00
},
unmounted() {
this.texture.dispose();
2020-09-19 22:41:26 +08:00
this.material.dispose();
},
methods: {
onLoaded() {
2021-03-07 06:14:22 +08:00
this.loading = false;
2020-09-19 22:41:26 +08:00
this.updateUV();
this.$emit('loaded');
},
updateUV() {
this.iWidth = this.texture.image.width;
this.iHeight = this.texture.image.height;
this.iRatio = this.iWidth / this.iHeight;
let x = 0.5, y = 0.5;
if (this.iRatio > 1) {
y = 0.5 / this.iRatio;
} else {
x = 0.5 / this.iRatio;
}
const positions = this.geometry.attributes.position.array;
positions[0] = -x; positions[1] = -y;
positions[5] = x; positions[6] = -y;
positions[10] = x; positions[11] = y;
positions[15] = -x; positions[16] = y;
this.geometry.attributes.position.needsUpdate = true;
},
2020-09-19 18:16:16 +08:00
},
2020-09-19 22:41:26 +08:00
__hmrId: 'Sprite',
2020-09-19 18:16:16 +08:00
};