...

/

Rendering to a Canvas and Using It as a Texture

Rendering to a Canvas and Using It as a Texture

Learn how to use HTML canvas as texture for the Three.js scene.

We'll cover the following...

So far, we’ve only used static images for our textures. However, Three.js also has the option to use the HTML5 canvas as a texture.

We will look at two different examples.

  • First, we will look at how we can use the canvas to create a simple texture and apply it to a mesh.

  • After that, we’ll go one step further and create a canvas that can be used as a bump map using a randomly generated pattern.

Using the canvas as a color map

In this first example, we’ll render a fractal to an HTML canvas element and use that as a color map for our mesh. The following screenshot shows the output of this example:

Using an HTML canvas as a texture
Using an HTML canvas as a texture

Example: Canvas as color map

Let’s execute the texture-canvas-as-color-map.js example in the playground below by clicking the “Run” button:

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
// const CopyWebpackPlugin = require('copy-webpack-plugin')
const fs = require('fs').promises

// we should search through the directories in examples, and use
// the name from the files to generate the HtmlWebpackPlugin settings.
module.exports = async () => {

  return {
    module: {
      rules: [
        {
          test: /\.glsl$/i,
          use: 'raw-loader'
        }
      ]
    },
    mode: 'development',
    entry: {
      'chapter-10': './samples/chapters/chapter-10/texture-canvas-as-color-map.js',
    },
    output: {
      path: path.resolve(__dirname, 'dist'),
      filename: 'bundle.js',
      publicPath: '/',
    },
    plugins: [
      new HtmlWebpackPlugin(),
    ],
    experiments: {
      asyncWebAssembly: true
    },
    devServer: {
       allowedHosts: 'all',
       host: '0.0.0.0',
       port: '3000',
       static: [
        {
          directory: path.join(__dirname, 'assets'),
          publicPath: '/assets'
        },
        {
          directory: path.join(__dirname, 'dist')
        }
      ] 
    },
  mode: 'development',
  }
}
Set canvas as color map property of material

Note: We can change the properties of the color map from the right control panel in the output screen.

First, we’ll look at the code required to render the fractal:

import Mandelbrot from 'mandelbrot-canvas'
...
const div = document.createElement('div')
div.id = 'mandelbrot'
div.style = 'position: absolute'
document.body.append(div)
const mandelbrot = new Mandelbrot(document.
getElementById('mandelbrot'), {
height: 300,
width: 300,
magnification: 100
})
mandelbrot.render()

We won’t go into too much detail, but this library requires a div element as input (lines 3–6) and will create a canvas element inside that div (lines 7–12 ...