如何在 three.js 中实时更改片段着色器?

How can I change fragment shader in realtime in three.js?

我做了显而易见的事情,但它不起作用:

myshader.fragmentShader = myfragmentshader; //string

documentation所述:

Built in attributes and uniforms are passed to the shaders along with your code. If you don't want the WebGLProgram to add anything to your shader code, you can use RawShaderMaterial instead of this class. You can use the directive #pragma unroll_loop in order to unroll a for loop in GLSL by the shader preprocessor. The directive has to be placed right above the loop. The loop formatting has to correspond to a defined standard

three.js 的过程可以在 RawShaderMaterial 文档中找到。

这是一个很好的方法,因为我们是从 material 级别开始的。这意味着您可以为每个 material 自定义着色器设置它,而不是为 webGL 应用程序中的所有对象设置它。

var material = new THREE.RawShaderMaterial( {

    uniforms: {
        time: { value: 1.0 }
    },
    vertexShader: document.getElementById( 'vertexShader' ).textContent,
    fragmentShader: document.getElementById( 'fragmentShader' ).textContent,

} );

在运行时只需设置 material 经典 three.js 简单风格:

  object3d.material = raw_mat;