Skip to content

Instantly share code, notes, and snippets.

@mattatz
Last active January 26, 2021 15:43
Show Gist options
  • Save mattatz/305cc4684f3a1893e93fff5a47f40ca6 to your computer and use it in GitHub Desktop.
Save mattatz/305cc4684f3a1893e93fff5a47f40ca6 to your computer and use it in GitHub Desktop.
Vertical linear gradient colored cube texture in three.js
// Vertical gradient cube texture
export default class GradientCubeTexture extends THREE.CubeTexture {
constructor(bottom = '#4488aa', top = '#aaddff', size = 32) {
super()
// px, nx, py, ny, pz, nz
this.images[0] = this.create(top, bottom, size)
this.images[1] = this.create(top, bottom, size)
this.images[2] = this.create(top, top, size)
this.images[3] = this.create(bottom, bottom, size)
this.images[4] = this.create(top, bottom, size)
this.images[5] = this.create(top, bottom, size)
this.needsUpdate = true
}
create(color0, color1, size) {
let canvas = document.createElement('canvas')
canvas.width = canvas.height = size
let context = canvas.getContext('2d')
// create vertical linear gradient
let grad = context.createLinearGradient(0, 0, 0, size)
grad.addColorStop(0, color0)
grad.addColorStop(1, color1)
context.fillStyle = grad
context.fillRect(0, 0, size, size)
let img = context.getImageData(0, 0, size, size)
// stride of THREE.DataTexture array is 3
// Convert stride:4 to stride:3
let pixels = new Uint8Array(size * size * 3)
for (let i = 0; i < img.data.length; i += 4) {
let r = img.data[i]
let g = img.data[i + 1]
let b = img.data[i + 2]
let idx = i / 4 * 3
pixels[idx] = r
pixels[idx + 1] = g
pixels[idx + 2] = b
}
let texture = new THREE.DataTexture(pixels, size, size, THREE.RGBFormat)
// Following approaches cause CubeTexture error in v0.111.0:
// THREE.WebGLState: TypeError: Failed to execute 'texImage2D' on 'WebGLRenderingContext': No function was found that matched the signature provided.
/*
let texture = new THREE.Texture()
texture.minFilter = THREE.LinearFilter
texture.image = canvas
texture.needsUpdate = true
*/
// texture = new THREE.CanvasTexture(canvas)
// debug
// document.body.appendChild(canvas)
return texture
}
}
@mattatz
Copy link
Author

mattatz commented Dec 11, 2019

gradient-cube-texture

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment