WordPress に簡単に Three.js を導入できるプラグイン「ThreeWP」

ちょっと色々遊んでいたら、Three.js を WordPress に簡単に導入できるプラグインがあったので、ご紹介。

Three.js とは?

手軽に3Dコンテンツを制作できるJavaScriptライブラリで、本家サイトはこちら。WebGL を利用して描画を行なう。わたくしはほとんどわかっていないけど、「three.js」で検索すれば色々サンプルコードが出てくる。

Three.js を WordPress で利用できるプラグイン「ThreeWP」

まあ、Three.js を導入するためには CDN から three.js を読み込んで別途、レンダリングするスクリプトを書いてやればよい。WordPress であれば、wp_enqueue_script で読み込んでということになるけど、簡単に導入でプラグインが「ThreeWP」。

インストールは WordPress の管理画面から「プラグイン>プラグインを追加」で「ThreeWP」で検索。

ThreeWP インストール

「今すぐインストール」で有効化するだけ。設定はなどはない。

それで使い方としてはショート[use_threewp]を three.js を使用したい投稿に挿入する。そうするとその投稿で three.js が読み込まれる。それで表示させたい 3D は当然、スクリプトを書いてやらねばならない。

ってことで、プラグインページにあるスクリプトを一部改変して埋め込んでやることにした。以下のコードをテーマの js フォルダに three-test.js としてアップする

document.addEventListener('DOMContentLoaded', function () {
    if (typeof ThreeWP !== 'undefined') {
        // Destructure THREE and THREE_ADDONS from ThreeWP
        const { THREE, OrbitControls } = ThreeWP;
        // Create a scene
        const scene = new THREE.Scene();
        // Setup a camera
        const camera = new THREE.PerspectiveCamera(
            75,
            window.innerWidth / window.innerHeight,
            0.1,
            1000,
        );
        // Setup a renderer
        const renderer = new THREE.WebGLRenderer();
        // Give the renderer a width and height
        renderer.setSize(720, 480); // 改変

        // Append the renderer into the html body
        const container = document.getElementById('threewp-container'); // 改変
        container.appendChild(renderer.domElement);  // 改変

        // Set camera position
        camera.position.z = 2;
        // Load a texture
        const textureLoader = new THREE.TextureLoader();
        const texture = textureLoader.load(
            'https://threejsfundamentals.org/threejs/resources/images/wall.jpg',
        ); // Replace with your image URL
        // Create geometry
        const geometry = new THREE.BoxGeometry(1, 1, 1);
        // Create material
        const material = new THREE.MeshStandardMaterial({ map: texture });
        // Combine into mesh
        const sphere = new THREE.Mesh(geometry, material);
        scene.add(sphere);
        const light = new THREE.AmbientLight(0xffffff);
        scene.add(light);
        // Set up OrbitControls
        const controls = new OrbitControls(
            camera,
            renderer.domElement,
        );
        // Optional: Adjust controls settings (e.g., damping, auto-rotation)
        controls.enableDamping = true; // Adds smoothness when dragging
        controls.dampingFactor = 0.03;
        controls.autoRotate = true;
        controls.autoRotateSpeed = 2;
        function animate(t = 0) {
            requestAnimationFrame(animate);
            controls.update();
            renderer.render(scene, camera);
        }
        animate();
        container.style.display="block"; // 追加
        // Responsive
        window.addEventListener('resize', () => {
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            // renderer.setSize(window.innerWidth, window.innerHeight); コメントアウト
        });
    } else {
        console.error('Three.js could not be loaded.');
    }
});

改変のポイントとしては、[use_threewp] を投稿に埋め込むと、

<div id="threewp-container" style="display: none;"></div>

が挿入されるようなので、これに renderer をサイズ指定して入れてやることにした。これを

wp_enqueue_script( 'three-test', get_stylesheet_directory_uri() . '/js/three-test.js', array(), '1.0.0', true );

で目的の投稿で読み込んでやる。

その上で、3D を埋め込みたいところにショートコード[use_threewp] を入れてやる。その結果が、以下になる。

このプラグインでは CDN の three.js ではなく、プラグインにバンドルされた three.js を読み込むよう。まあ普通に CDN を読み込むか、CDN 避けたい場合でも自分で読み込んでやればいいわけだから、とくにこのプラグイン入れなくてもいいけど、まあ楽は楽でしょうか。最終更新が1年前になってるので、three.js が最新版ではないかな…。

あと、「CSS & JavaScript Toolbox」のようなプラグインを使えば上記のようなスクリプトを管理画面から挿入することができ、管理画面だけで完結。テーマファイルをいじる必要はなくなりますね。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です