Skip to content

Transparent Shadow

Description

This is an experiment where I tried to create a shadow from a transparent texture. I was able to get halfway to what I wanted to achieve by using a grayscale image as an alpha map. I could then cut out at certain grayness depending on the materials alphaTest property. Slide the alphaTest slider in the example. Caveat, there may be a better way to do this, I haven't tried yet.

<>

Example Script

./src/client/client.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import Stats from 'three/examples/jsm/libs/stats.module'
import { GUI } from 'dat.gui'

const scene = new THREE.Scene()

const light1 = new THREE.PointLight(0xffffff, 1000)
light1.position.set(10, 10, 10)
light1.castShadow = true
light1.shadow.mapSize.height = 1024
light1.shadow.mapSize.width = 1024
scene.add(light1)

const camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
)
camera.position.set(-2.5, 0, 5)

const renderer = new THREE.WebGLRenderer({ antialias: true })
renderer.shadowMap.enabled = true
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)

const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true

window.addEventListener('resize', onWindowResize, false)
function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
    render()
}

var loader = new THREE.TextureLoader()
var texture = loader.load('img/grid.png')
var alphaMap = loader.load('img/grayscale-test.png')

var material = new THREE.MeshStandardMaterial({
    map: texture,
    alphaMap: alphaMap,
    side: THREE.DoubleSide,
    transparent: true,
    alphaTest: 0.5,
})

const wall = new THREE.Mesh(new THREE.PlaneGeometry(5, 5), material)
wall.position.set(0, 0, 0)
wall.castShadow = true
scene.add(wall)

const floorMaterial = new THREE.MeshPhongMaterial()
const floor = new THREE.Mesh(new THREE.PlaneGeometry(20, 20), floorMaterial)
floor.rotateX(-Math.PI / 2)
floor.position.set(0, -2, 0)
floor.receiveShadow = true
scene.add(floor)

const stats = new Stats()
document.body.appendChild(stats.dom)

const gui = new GUI()
gui.add(material, 'alphaTest', 0, 1, 0.01).onChange((v) => {
    material.needsUpdate = true
})

var animate = function () {
    requestAnimationFrame(animate)

    controls.update()

    render()

    stats.update()
}

function render() {
    renderer.render(scene, camera)
}
animate()

Comments