简体   繁体   中英

Particular Wp Enqueue script in wordpress

When looking for a plugin, I ended up across this website

I saw that there is a nice cloud animation .

So I started a search on google to find the source of the code and I found it here ... Preview

/JS

<script type="text/javascript" src="js/ThreeWebGL.js"></script>
<script type="text/javascript" src="js/ThreeExtras.js"></script>
<script type="text/javascript" src="js/Detector.js"></script>
<script type="text/javascript" src="js/RequestAnimationFrame.js"></script>

/Html

<script id="vs" type="x-shader/x-vertex">
    varying vec2 vUv;
    void main() {
        vUv = uv;
        gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
    }
</script>
<script id="fs" type="x-shader/x-fragment">
    uniform sampler2D map;
    uniform vec3 fogColor;
    uniform float fogNear;
    uniform float fogFar;
    varying vec2 vUv;
    void main() {
        float depth = gl_FragCoord.z / gl_FragCoord.w;
        float fogFactor = smoothstep( fogNear, fogFar, depth );
        gl_FragColor = texture2D( map, vUv );
        gl_FragColor.w *= pow( gl_FragCoord.z, 20.0 );
        gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );
    }
</script>
<script type="text/javascript">
    if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
    // Bg gradient
    var canvas = document.createElement( 'canvas' );
    canvas.width = 32;
    canvas.height = window.innerHeight;
    var context = canvas.getContext( '2d' );
    var gradient = context.createLinearGradient( 0, 0, 0, canvas.height );
    gradient.addColorStop(0, "#1e4877");
    gradient.addColorStop(0.5, "#4584b4");
    context.fillStyle = gradient;
    context.fillRect(0, 0, canvas.width, canvas.height);
    document.body.style.background = 'url(' + canvas.toDataURL('image/png') + ')';
    // Clouds
    var container;
    var camera, scene, renderer, sky, mesh, geometry, material,
    i, h, color, colors = [], sprite, size, x, y, z;
    var mouseX = 0, mouseY = 0;
    var start_time = new Date().getTime();
    var windowHalfX = window.innerWidth / 2;
    var windowHalfY = window.innerHeight / 2;
    init();
    animate();
    function init() {
        container = document.createElement( 'div' );
        document.body.appendChild( container );
        camera = new THREE.Camera( 30, window.innerWidth / window.innerHeight, 1, 3000 );
        camera.position.z = 6000;
        scene = new THREE.Scene();
        geometry = new THREE.Geometry();
        var texture = THREE.ImageUtils.loadTexture( 'cloud10.png' );
        texture.magFilter = THREE.LinearMipMapLinearFilter;
        texture.minFilter = THREE.LinearMipMapLinearFilter;
        var fog = new THREE.Fog( 0x4584b4, - 100, 3000 );
        material = new THREE.MeshShaderMaterial( {
            uniforms: {
                "map": { type: "t", value:2, texture: texture },
                "fogColor" : { type: "c", value: fog.color },
                "fogNear" : { type: "f", value: fog.near },
                "fogFar" : { type: "f", value: fog.far },
            },
            vertexShader: document.getElementById( 'vs' ).textContent,
            fragmentShader: document.getElementById( 'fs' ).textContent,
            depthTest: false
        } );
        var plane = new THREE.Mesh( new THREE.Plane( 64, 64 ) );
        for ( i = 0; i < 8000; i++ ) {
            plane.position.x = Math.random() * 1000 - 500;
            plane.position.y = - Math.random() * Math.random() * 200 - 15;
            plane.position.z = i;
            plane.rotation.z = Math.random() * Math.PI;
            plane.scale.x = plane.scale.y = Math.random() * Math.random() * 1.5 + 0.5;
            GeometryUtils.merge( geometry, plane );
        }
        mesh = new THREE.Mesh( geometry, material );
        scene.addObject( mesh );
        mesh = new THREE.Mesh( geometry, material );
        mesh.position.z = - 8000;
        scene.addObject( mesh );
        renderer = new THREE.WebGLRenderer( { antialias: false } );
        renderer.setSize( window.innerWidth, window.innerHeight );
        container.appendChild( renderer.domElement );
        document.addEventListener( 'mousemove', onDocumentMouseMove, false );
        window.addEventListener( 'resize', onWindowResize, false );
    }
    function onDocumentMouseMove( event ) {
        mouseX = ( event.clientX - windowHalfX ) * 0.25;
        mouseY = ( event.clientY - windowHalfY ) * 0.15;
    }
    function onWindowResize( event ) {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize( window.innerWidth, window.innerHeight );
    }
    function animate() {
        requestAnimationFrame( animate );
        render();
    }
    function render() {
        position = ( ( new Date().getTime() - start_time ) * 0.03 ) % 8000;
        camera.position.x += ( mouseX - camera.target.position.x ) * 0.01;
        camera.position.y += ( - mouseY - camera.target.position.y ) * 0.01;
        camera.position.z = - position + 8000;
        camera.target.position.x = camera.position.x;
        camera.target.position.y = camera.position.y;
        camera.target.position.z = camera.position.z - 1000;
        renderer.render( scene, camera );
    }
</script>

My question now :

I would like to set it up on my localhost site to test it on elementor.

I will call the script with an html widget.

The problem I know there is an wp_enqueue_script option in functions.php and the script goes there ..

but I can't understand the exact procedure. I failed for hours to set up the scripts ...

Can you show me how to integrate it ? I need a good example how use these scripts. to understand once and for all how to integrate scripts in wordpress child themes.

My setup : A clean install of wordpress with an empty hello theme and it's child installed .

Update

let's develop the subject a bit I did these manipulations in functions.php

function my_scripts_method() {
    wp_enqueue_script('custom-script',get_stylesheet_directory_uri() . '/js/ThreeWebGL.js',array( 'jquery' ));
    wp_enqueue_script('custom-script',get_stylesheet_directory_uri() . '/js/ThreeExtras.js',array( 'jquery' ));
    wp_enqueue_script('custom-script',get_stylesheet_directory_uri() . '/js/Detector.js',array( 'jquery' ));
    wp_enqueue_script('custom-script',get_stylesheet_directory_uri() . '/js/RequestAnimationFrame.js',array( 'jquery' ));

}

add_action( 'wp_enqueue_scripts', 'my_scripts_method' );

It seems to work.. the scripts are loaded I hope.

I just have a message in the chrome console :

Uncaught ReferenceError: Detector is not defined at (index): 117

I guess because i haven't put html yet?

what do you think of a snippet ?

I use it to create and add_shortcode

something like that.. do you think it's safe ?

    add_shortcode( 'amazing clouds', function () {

<script id="vs" type="x-shader/x-vertex">
    varying vec2 vUv;
    void main() {
        vUv = uv;
        gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
    }
</script>
<script id="fs" type="x-shader/x-fragment">
    uniform sampler2D map;
    uniform vec3 fogColor;
    uniform float fogNear;
    uniform float fogFar;
    varying vec2 vUv;
    void main() {
        float depth = gl_FragCoord.z / gl_FragCoord.w;
        float fogFactor = smoothstep( fogNear, fogFar, depth );
        gl_FragColor = texture2D( map, vUv );
        gl_FragColor.w *= pow( gl_FragCoord.z, 20.0 );
        gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );
    }
</script>
<script type="text/javascript">
    if ( ! Detector.webgl ) Detector.addGetWebGLMessage();
    // Bg gradient
    var canvas = document.createElement( 'canvas' );
    canvas.width = 32;
    canvas.height = window.innerHeight;
    var context = canvas.getContext( '2d' );
    var gradient = context.createLinearGradient( 0, 0, 0, canvas.height );
    gradient.addColorStop(0, "#1e4877");
    gradient.addColorStop(0.5, "#4584b4");
    context.fillStyle = gradient;
    context.fillRect(0, 0, canvas.width, canvas.height);
    document.body.style.background = 'url(' + canvas.toDataURL('image/png') + ')';
    // Clouds
    var container;
    var camera, scene, renderer, sky, mesh, geometry, material,
    i, h, color, colors = [], sprite, size, x, y, z;
    var mouseX = 0, mouseY = 0;
    var start_time = new Date().getTime();
    var windowHalfX = window.innerWidth / 2;
    var windowHalfY = window.innerHeight / 2;
    init();
    animate();
    function init() {
        container = document.createElement( 'div' );
        document.body.appendChild( container );
        camera = new THREE.Camera( 30, window.innerWidth / window.innerHeight, 1, 3000 );
        camera.position.z = 6000;
        scene = new THREE.Scene();
        geometry = new THREE.Geometry();
        var texture = THREE.ImageUtils.loadTexture( 'cloud10.png' );
        texture.magFilter = THREE.LinearMipMapLinearFilter;
        texture.minFilter = THREE.LinearMipMapLinearFilter;
        var fog = new THREE.Fog( 0x4584b4, - 100, 3000 );
        material = new THREE.MeshShaderMaterial( {
            uniforms: {
                "map": { type: "t", value:2, texture: texture },
                "fogColor" : { type: "c", value: fog.color },
                "fogNear" : { type: "f", value: fog.near },
                "fogFar" : { type: "f", value: fog.far },
            },
            vertexShader: document.getElementById( 'vs' ).textContent,
            fragmentShader: document.getElementById( 'fs' ).textContent,
            depthTest: false
        } );
        var plane = new THREE.Mesh( new THREE.Plane( 64, 64 ) );
        for ( i = 0; i < 8000; i++ ) {
            plane.position.x = Math.random() * 1000 - 500;
            plane.position.y = - Math.random() * Math.random() * 200 - 15;
            plane.position.z = i;
            plane.rotation.z = Math.random() * Math.PI;
            plane.scale.x = plane.scale.y = Math.random() * Math.random() * 1.5 + 0.5;
            GeometryUtils.merge( geometry, plane );
        }
        mesh = new THREE.Mesh( geometry, material );
        scene.addObject( mesh );
        mesh = new THREE.Mesh( geometry, material );
        mesh.position.z = - 8000;
        scene.addObject( mesh );
        renderer = new THREE.WebGLRenderer( { antialias: false } );
        renderer.setSize( window.innerWidth, window.innerHeight );
        container.appendChild( renderer.domElement );
        document.addEventListener( 'mousemove', onDocumentMouseMove, false );
        window.addEventListener( 'resize', onWindowResize, false );
    }
    function onDocumentMouseMove( event ) {
        mouseX = ( event.clientX - windowHalfX ) * 0.25;
        mouseY = ( event.clientY - windowHalfY ) * 0.15;
    }
    function onWindowResize( event ) {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize( window.innerWidth, window.innerHeight );
    }
    function animate() {
        requestAnimationFrame( animate );
        render();
    }
    function render() {
        position = ( ( new Date().getTime() - start_time ) * 0.03 ) % 8000;
        camera.position.x += ( mouseX - camera.target.position.x ) * 0.01;
        camera.position.y += ( - mouseY - camera.target.position.y ) * 0.01;
        camera.position.z = - position + 8000;
        camera.target.position.x = camera.position.x;
        camera.target.position.y = camera.position.y;
        camera.target.position.z = camera.position.z - 1000;
        renderer.render( scene, camera );
    }
</script>
} );

Things got very complicated very quickly.

I hope someone will come and show us how to integrate it into a wordpress page

(with elementor is bonus)

The HTML widget will strip out php tags for security reasons. But you have several options which will allow you to achieve your goal. Here are three:

  1. Edit your child theme's functions.php file to allow php in the widget. (Bad idea)

  2. Write your own custom widget which enqueues the script you need. (Better idea)

  3. Don't use a widget at all. Just add the script to the pages you want it using the Advanced Custom Fields plugin. (Best idea IMHO)

And since you asked about loading JS, here's a good resource for you.
And here's another on the topic of wp_enqueue_scripts() .


Edit: step by step instructions for ACF plugin:

  1. Install Advanced Custom Fields plugin
  2. Go to the Custom Fields settings and click Add New
  3. Name the field group something like “Javascript Settings”
  4. Create rules to restrict where the fields will appear and who will see them
  5. Next to Style, choose Standard (WP metabox)
  6. Click + Add Field
  7. Name it “Header Script”
  8. Change Field Type to “Text Area”
  9. Change Formatting to “Convert HTML to tags”
  10. Repeat from step 6, but this time call it “Footer Script”
  11. Publish the Field Group
  12. In header.php, right before the closing </head> tag, add: <?php the_field('header_script'); ?> <?php the_field('header_script'); ?>
  13. In footer.php, right before the closing </body> tag, add: <?php the_field('footer_script'); ?> <?php the_field('footer_script'); ?>
  14. Place your javascript files in a folder on your server (preferably in a child theme).
  15. Link your javascript in the new fields on your page using regular html <script> tags

Note: copy your header.php and footer.php files into your child theme and make the edits (steps 12 & 13) there to avoid losing these changes if your theme is updated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM