Estou tentando recriar esta incrível simulação de onda: https://codepen.io/cheekymonkey/pen/vMvYNV, em Vue.js. No entanto, a animação é muito lenta quando eu a recriei no Vue.js
Tentei fazer todas as mesmas funções dos métodos Vue.js e incluir as variáveis na propriedade de dados do componente.
<template>
<div id="container" style="width:100%; height:100vh;"></div>
</template>
<script>
import * as Three from 'three'
import SimplexNoise from'simplex-noise'
export default {
name: 'ThreeTest',
data() {
return {
camera: Three.PerspectiveCamera,
scene: Three.Scene,
renderer: Three.WebGLRenderer,
mesh: Three.Mesh,
noise: SimplexNoise,
geometry: null,
factor: 0
}
},
methods: {
init: function() {
this.createScene();
this.createCamera();
this.createShape();
this.addSpotlight('#fdffab');
this.addAmbientLight();
this.animate();
window.addEventListener('resize', this.onResize())
},
onResize: function() {
let container = document.getElementById('container');
this.renderer.setSize(container.clientWidth, container.clientHeight);
this.camera.aspect = container.clientWidth / container.clientHeight;
this.camera.updateProjectionMatrix();
},
createScene: function() {
this.scene = new Three.Scene();
this.renderer = new Three.WebGLRenderer({
antialias: true,
alpha: true
});
let container = document.getElementById('container');
this.renderer.setSize(container.clientWidth, container.clientHeight);
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setClearColor(new Three.Color('#fff'));
//this.render.shadowMap.type = Three.PCFSoftShadowMap;
this.noise = new SimplexNoise()
container.appendChild(this.renderer.domElement);
},
createCamera: function() {
this.camera = new Three.PerspectiveCamera(20, container.clientWidth/container.clientHeight, 1, 1000);
this.camera.position.set(0, 0, 20);
},
createShape: function() {
const seg = 100
this.geometry = new Three.PlaneGeometry(5, 8, seg, seg)
const material = new Three.MeshPhysicalMaterial({
color: '#da0463',
metalness: 0.6,
emissive: '#000',
side: Three.DoubleSide,
wireframe: true
})
this.mesh = new Three.Mesh(this.geometry, material)
this.mesh.receiveShadow = true
this.mesh.castShadow = true
this.mesh.position.set(0, 0, 0)
this.mesh.rotation.x = -Math.PI / 3
this.mesh.rotation.z = -Math.PI / 4
this.scene.add(this.mesh)
},
addSpotlight: function(color) {
const light = new Three.SpotLight(color, 2, 1000)
light.position.set(0, 0, 30)
this.scene.add(light)
},
addAmbientLight: function() {
const light = new Three.AmbientLight('#fff', 0.5)
this.scene.add(light)
},
addjustVertices: function() {
for (let i = 0; i < this.geometry.vertices.length; i++) {
const vertex = this.geometry.vertices[i]
const x = vertex.x / 4
const y = vertex.y / 6
vertex.z = this.noise.noise2D(x, y + this.factor)
}
this.factor += 0.007
this.geometry.verticesNeedUpdate = true
this.geometry.computeVertexNormals()
},
animate: function() {
requestAnimationFrame(this.animate);
this.addjustVertices();
this.camera.updateProjectionMatrix();
this.renderer.render(this.scene, this.camera);
}
},
mounted() {
this.init();
}
}
</script>
Funciona, como na animação de onda, como deveria, mas é muito mais lento. Não tenho certeza se isso é devido ao Vue.js ou apenas como eu o configurei. Qualquer conselho muito apreciado!
Isso está ocorrendo porque o Vue sob o capô torna cada componente anexado à instância reativo. Reatividade em profundidade . Abra as ferramentas de desenvolvimento e olhe para sua pegada de memória, quando eu executei seu snippet em minha máquina, ele é de aproximadamente 300 MB ao contrário do exemplo do codepen que é de aproximadamente 20 MB.
Quando você console.log(this.scene)vê, são os getters / setters que permitem ao Vue rastrear objetos.

O snippet a seguir puxa os objetos three.js do objeto de dados Vue e os anexa a um objeto estático vue . Este plugin permite que você defina certas variáveis como não reativas.
<template>
<div id="container" style="width:100%; height:100vh;"></div>
</template>
<script>
import * as Three from 'three'
import SimplexNoise from'simplex-noise'
export default {
name: 'ThreeTest',
static(){
return {
scene: new Three.Scene(),
camera: null,
renderer: Three.WebGLRenderer,
mesh: new Three.Mesh,
noise: SimplexNoise,
factor:0
}
},
mounted() {
this.init();
},
methods: {
init: function() {
this.createScene();
this.createCamera();
this.createShape();
this.addSpotlight('#fdffab');
this.addAmbientLight();
this.animate();
window.addEventListener('resize', this.onResize())
},
onResize: function() {
let container = document.getElementById('container');
this.renderer.setSize(container.clientWidth, container.clientHeight);
this.camera.aspect = container.clientWidth / container.clientHeight;
this.camera.updateProjectionMatrix();
},
createScene: function() {
console.log("TCL: this.$options.bigHairyHorseNuts ",this.bigHairyHorseNuts)
this.renderer = new Three.WebGLRenderer({
antialias: true,
alpha: true
});
let container = document.getElementById('container');
this.renderer.setSize(container.clientWidth, container.clientHeight);
this.renderer.setPixelRatio(window.devicePixelRatio);
this.renderer.setClearColor(new Three.Color('#fff'));
//this.render.shadowMap.type = Three.PCFSoftShadowMap;
this.noise = new SimplexNoise()
container.appendChild(this.renderer.domElement);
},
createCamera: function() {
this.camera = new Three.PerspectiveCamera(20, container.clientWidth/container.clientHeight, 1, 1000);
this.camera.position.set(0, 0, 20);
},
createShape: function() {
const seg = 100
this.geometry = new Three.PlaneGeometry(5, 8, seg, seg)
const material = new Three.MeshPhysicalMaterial({
color: '#da0463',
metalness: 0.6,
emissive: '#000',
side: Three.DoubleSide,
wireframe: true
})
this.mesh = new Three.Mesh(this.geometry, material)
this.mesh.receiveShadow = true
this.mesh.castShadow = true
this.mesh.position.set(0, 0, 0)
this.mesh.rotation.x = -Math.PI / 3
this.mesh.rotation.z = -Math.PI / 4
this.scene.add(this.mesh)
},
addSpotlight: function(color) {
const light = new Three.SpotLight(color, 2, 1000)
light.position.set(0, 0, 30)
this.scene.add(light)
},
addAmbientLight: function() {
const light = new Three.AmbientLight('#fff', 0.5)
this.scene.add(light)
},
addjustVertices: function() {
for (let i = 0; i < this.geometry.vertices.length; i++) {
const vertex = this.geometry.vertices[i]
const x = vertex.x / 4
const y = vertex.y / 6
vertex.z = this.noise.noise2D(x, y + this.factor)
}
this.factor += 0.007
this.geometry.verticesNeedUpdate = true
this.geometry.computeVertexNormals()
},
animate: function() {
requestAnimationFrame(this.animate);
this.addjustVertices();
this.camera.updateProjectionMatrix();
this.renderer.render(this.scene, this.camera);
}
}
}
</script>
Jana Duggar foi aberta sobre sua busca pelo amor. Aqui está tudo o que ela disse sobre o assunto e sua janela de cinco anos para o casamento.
O astro de 'Outlander', Sam Heughan, revelou recentemente o que vai levar do set para relembrar Jamie Fraser, o papel que o tornou uma estrela.
'She Loves You' foi escrita em uma hora, gravada em um dia, e foi a música dos Beatles com uma de suas melhores apresentações de sua carreira.
Dolly Parton e sua avó Bessie tiveram um relacionamento especial. Vovó Parton estava muito doente, mas isso não impediu Dolly de pregar uma peça nela.
Você pode achar que o carvalho ou a nogueira são madeiras resistentes, mas quando se trata da madeira mais dura do mundo, elas nem chegam perto.
O oceano é repleto de beleza, mas também esconde algumas das criaturas marinhas mais assustadoras do planeta. Muitos desses animais espreitam nas profundezas do oceano, no mundo escuro e de alta pressão do fundo do mar.
Se você está enfrentando criaturas hostis ou se preparando para cenários PvP, conhecer os melhores encantamentos de espada no Minecraft pode te dar uma grande vantagem. Encantar espadas permite causar mais dano, aumentar a quantidade de itens obtidos de criaturas e prolongar a durabilidade da sua espada.
Quando as pessoas falam sobre países socialistas, geralmente imaginam o controle total do governo e a ausência de propriedade privada. Mas, na prática, as economias socialistas variam muito.
“Children” traz uma participação especial de grande nome e algumas notícias devastadoras
Este RAV4 está em excelentes condições e está preparado para um jogo de cadeiras musicais.
Imagens de drone capturaram bombeiros parecendo lutar para apagar o incêndio.
Eyes of Wakanda está diretamente relacionado ao MCU, além de atualizações sobre X-Men '97, What If..., Demolidor e muito mais.
O anel de noivado de Kate Middleton pertenceu à Princesa Diana antes do Príncipe William pedi-la em casamento. Descubra tudo o que há para saber sobre a peça histórica aqui.
John Cleese se casou com sua esposa, Jennifer Wade, em 2012. Aqui está tudo o que você precisa saber sobre a esposa de John Cleese, Jennifer Wade.
Patton Oswalt se casou com sua esposa, a também atriz Meredith Salenger, em 2017. Aqui está tudo o que você precisa saber sobre a esposa de Patton Oswalt, Meredith Salenger.
Mena Suvari é casada com o marido Michael Hope desde 2018. Aqui está tudo o que você precisa saber sobre o marido de Mena Suvari.
Isso me atinge De repente, como tantas vezes acontece É o meio do caminho tudo de novo <Não, não aquele no Pacífico, seu marrom, aquele no carnaval> Todas as manchetes em voz alta…..
Em 2022, com o lançamento do GPT-3, a habilidade de escrita parece se tornar menos importante. Com a IA, pessoas com redação ruim também podem gerar funcionários de qualidade.
No mundo acelerado e competitivo de hoje, a carreira desempenha um papel significativo no crescimento pessoal, na estabilidade financeira e na satisfação geral com a vida. No entanto, muitos indivíduos encontram-se presos em um ciclo implacável de estagnação e insatisfação, definhando gradualmente em suas vidas profissionais.
Na semana passada, notei um comunicado de imprensa, enviado via PressGazette (um site de notícias da mídia britânica). O artigo anunciava que a Acast, a empresa de publicidade e hospedagem de podcast Scandi, lideraria um consórcio de "provavelmente os editores mais influentes" em podcasting.