Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <canvas id="canvas"></canvas>
<div class="container">
</div>
<div class="links">
   <a href="https://tympanus.net/codrops/2023/03/28/turning-3d-models-to-voxel-art-with-three-js/" target="_blank">tutorial<img class="icon" src="https://ksenia-k.com/img/icons/link.svg"></a>
</div>
<div id="copyright">
    <div>
        <a href="https://poly.pizza/m/8BsjISKsNIz" target="_blank">Cherry</a> by <a href="https://poly.pizza/u/Poly%20by%20Google" target="_blank">Poly by Google</a>&nbsp;[<a href="https://creativecommons.org/licenses/by/3.0/" target="_blank">CC-BY</a>] via Poly Pizza
    </div>
    <div>
        <a href="https://poly.pizza/m/44XK5UHTd4Q" target="_blank">Bonsai</a> by <a href="https://poly.pizza/u/Don%20Carson" target="_blank">Don Carson</a>&nbsp;[<a href="https://creativecommons.org/licenses/by/3.0/" target="_blank">CC-BY</a>] via Poly Pizza
    </div>
    <div>
        <a href="https://poly.pizza/m/2KHEgw1ztVI" target="_blank">Duck</a> by <a href="https://poly.pizza/u/jeremy" target="_blank">jeremy</a> [<a href="https://creativecommons.org/licenses/by/3.0/" target="_blank">CC-BY</a>] via Poly Pizza
    </div>
</div>

<script type="importmap">{
	"imports": {
		"three": "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.145.0/three.module.min.js",
		"three/addons/": "https://threejs.org/examples/jsm/"
	}
}
</script>
<script async src="https://unpkg.com/es-module-shims@1.6.3/dist/es-module-shims.js"></script>
              
            
!

CSS

              
                html, body {
    padding: 0;
    margin: 0;
    height: 100vh;
    background: radial-gradient(#e6d8f0, #ffe8e8);
    font-family: sans-serif;
}

.container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
}

.links {
    position: fixed;
    bottom: 20px;
    right: 20px;
    font-size: 18px;
}

.links a {
    text-decoration: none;
    color: black;
    margin-left: 1em;
}

.links a:hover {
    text-decoration: underline;
}

.links a img.icon {
    display: inline-block;
    height: 1em;
    margin: 0 0 -0.1em 0.3em;
}

#copyright {
    position: fixed;
    left: 10px;
    bottom: 10px;
    font-size: 10px;
    color: #3d3d3d;
}
              
            
!

JS

              
                import * as THREE from "three";
import {OrbitControls} from "three/addons/controls/OrbitControls.js";
import {GLTFLoader} from "three/addons/loaders/GLTFLoader.js";
import {RoundedBoxGeometry} from "three/addons/geometries/RoundedBoxGeometry.js";
import {GUI} from 'https://cdn.skypack.dev/lil-gui@0.16.1';

const containerEl = document.querySelector('.container');
const canvasEl = document.querySelector('#canvas');

let renderer, scene, mainCamera, mainOrbit, lightHolder;
let importedScene, instancedMesh, voxelGeometry, voxelMaterial;
let dummy, rayCaster, rayCasterIntersects = [];

let voxels = [];

const modelURLs = [
    "Cherry.glb",
    "Bonsai.glb",
    "Duck.glb"
];

const params = {
    modelSize: 8,
    gridSize: .2,
    boxSize: .2,
    boxRoundness: .05,
    model: modelURLs[0],
    showOriginal: false
}

createMainScene();
loadModel();
createControls();

window.addEventListener('resize', updateSceneSize);

function createMainScene() {

    // ------------------------------------
    // The scene

    renderer = new THREE.WebGLRenderer({
        canvas: canvasEl,
        alpha: true,
        antialias: true
    });
    renderer.shadowMap.enabled = true;
    renderer.shadowMapSoft = true;
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));

    scene = new THREE.Scene();

    mainCamera = new THREE.PerspectiveCamera(45, containerEl.clientWidth / containerEl.clientHeight, .01, 1000);
    mainCamera.position.set(0, .5, 2).multiplyScalar(8);

    rayCaster = new THREE.Raycaster();
    dummy = new THREE.Object3D();

    const ambientLight = new THREE.AmbientLight(0xffffff, .7);
    scene.add(ambientLight);

    lightHolder = new THREE.Group();
    const topLight = new THREE.SpotLight(0xffffff, .2);
    topLight.position.set(0, 15, 2);
    topLight.castShadow = true;
    topLight.shadow.camera.near = 10;
    topLight.shadow.camera.far = 30;
    topLight.shadow.mapSize = new THREE.Vector2(2048, 2048);
    lightHolder.add(topLight);
    const sideLight = new THREE.SpotLight(0xffffff, .4);
    sideLight.position.set(0, -4, 5);
    lightHolder.add(sideLight);
    scene.add(lightHolder);

    mainOrbit = new OrbitControls(mainCamera, containerEl);
    mainOrbit.enablePan = false;
    mainOrbit.autoRotate = true;
    mainOrbit.minDistance = 5;
    mainOrbit.maxDistance = 40;
    mainOrbit.autoRotateSpeed *= .5;
    mainOrbit.enableDamping = true;

    voxelGeometry = new RoundedBoxGeometry(params.boxSize, params.boxSize, params.boxSize, 1, params.boxRoundness);
    voxelMaterial = new THREE.MeshLambertMaterial({});

    const planeGeometry = new THREE.PlaneGeometry(100, 100);
    const shadowPlaneMaterial = new THREE.ShadowMaterial({
        opacity: .1
    });
    const shadowPlaneMesh = new THREE.Mesh(planeGeometry, shadowPlaneMaterial);
    shadowPlaneMesh.position.y = -4;
    shadowPlaneMesh.rotation.x = -.5 * Math.PI;
    shadowPlaneMesh.receiveShadow = true;
    lightHolder.add(shadowPlaneMesh);
}

function loadModel() {
    const loader = new GLTFLoader();
    loader.load('https://ksenia-k.com/models/' + params.model, (gltf) => {
        voxelizeModel(gltf.scene);

        createInstancedMesh(voxels.length);
        recreateVoxels();

        updateSceneSize();
        render();

        importedScene.visible = params.showOriginal;
        instancedMesh.visible = !params.showOriginal;
    }, undefined, (error) => {
        console.error(error);
    });
}

function voxelizeModel(loadedModel) {

    importedScene = loadedModel;

    const importedMeshes = [];
    importedScene.traverse((child) => {
        if (child instanceof THREE.Mesh) {
            child.material.side = THREE.DoubleSide;
            importedMeshes.push(child);
        }
    });

    let boundingBox = new THREE.Box3().setFromObject(importedScene);
    const size = boundingBox.getSize(new THREE.Vector3());
    const scaleFactor = params.modelSize / size.length();
    const center = boundingBox.getCenter(new THREE.Vector3()).multiplyScalar(-scaleFactor);

    importedScene.scale.multiplyScalar(scaleFactor);
    importedScene.position.copy(center);

    scene.add(importedScene);
    importedScene.visible = params.showOriginal;

    boundingBox = new THREE.Box3().setFromObject(importedScene);
    boundingBox.min.z -= .5 * params.gridSize;

    for (let i = boundingBox.min.x; i < boundingBox.max.x; i += params.gridSize) {
        for (let j = boundingBox.min.y; j < boundingBox.max.y; j += params.gridSize) {
            for (let k = boundingBox.min.z; k < boundingBox.max.z; k += params.gridSize) {
                for (let meshCnt = 0; meshCnt < importedMeshes.length; meshCnt++) {

                    const mesh = importedMeshes[meshCnt];
                    const pos = new THREE.Vector3(i, j, k);
                    const color = new THREE.Color();
                    const {h, s, l} = mesh.material.color.getHSL(color);
                    color.setHSL(h, s * .8, l * .7 + .3);

                    if (isInsideMesh(pos, {x: 0, y: 0, z: 1}, mesh)) {
                        voxels.push({color: color, position: pos});
                        break;
                    }
                }
            }
        }
    }
}

function isInsideMesh(pos, dir, mesh) {
    rayCaster.set(pos, dir);
    rayCasterIntersects = rayCaster.intersectObject(mesh, false);
    return rayCasterIntersects.length % 2 === 1;
}

function createInstancedMesh(cnt) {
    instancedMesh = new THREE.InstancedMesh(voxelGeometry, voxelMaterial, cnt);
    instancedMesh.castShadow = true;
    instancedMesh.receiveShadow = true;
    scene.add(instancedMesh);
}

function recreateVoxels() {
    for (let i = 0; i < voxels.length; i++) {
        instancedMesh.setColorAt(i, voxels[i].color);
        dummy.position.copy(voxels[i].position);
        dummy.updateMatrix();
        instancedMesh.setMatrixAt(i, dummy.matrix);
    }
    instancedMesh.instanceColor.needsUpdate = true;
    instancedMesh.instanceMatrix.needsUpdate = true;
}

function render() {
    mainOrbit.update();
    lightHolder.quaternion.copy(mainCamera.quaternion);
    renderer.render(scene, mainCamera);
    requestAnimationFrame(render);
}

function updateSceneSize() {
    mainCamera.aspect = containerEl.clientWidth / containerEl.clientHeight;
    mainCamera.updateProjectionMatrix();
    renderer.setSize(containerEl.clientWidth, containerEl.clientHeight);
}

function createControls() {
    const gui = new GUI();
    gui.add(params, "model", modelURLs).onChange(() => {
        voxels = [];
        scene.remove(instancedMesh, importedScene);
        loadModel();
    }).name("model name");
    gui.add(params, "showOriginal").onChange(v => {
        importedScene.visible = v;
        instancedMesh.visible = !v;
    }).name("show original scene");
}
              
            
!
999px

Console