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

62 lines
1.6 KiB
JavaScript
Raw Normal View History

2020-09-19 18:16:16 +08:00
import { Sprite, SpriteMaterial, TextureLoader } from 'three';
2021-02-22 04:39:35 +08:00
import { inject } from 'vue';
2020-09-19 18:16:16 +08:00
import useBindProp from '../use/useBindProp.js';
export default {
emits: ['ready', 'loaded'],
inject: ['three', 'scene'],
props: {
src: String,
position: Object,
2020-09-19 22:41:26 +08:00
scale: Object,
2020-09-19 18:16:16 +08:00
},
2021-02-22 04:39:35 +08:00
created() {
this.parent = inject('group', this.scene);
},
2020-09-19 18:16:16 +08:00
mounted() {
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;
2020-09-19 18:16:16 +08:00
useBindProp(this, 'position', this.sprite.position);
2020-09-19 22:41:26 +08:00
useBindProp(this, 'scale', this.sprite.scale);
2021-02-22 04:39:35 +08:00
this.parent.add(this.sprite);
2020-09-19 18:16:16 +08:00
this.$emit('ready');
},
unmounted() {
this.texture.dispose();
2020-09-19 22:41:26 +08:00
this.material.dispose();
2021-02-22 04:39:35 +08:00
this.parent.remove(this.sprite);
2020-09-19 22:41:26 +08:00
},
methods: {
onLoaded() {
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
},
render() {
return [];
},
2020-09-19 22:41:26 +08:00
__hmrId: 'Sprite',
2020-09-19 18:16:16 +08:00
};