Extruding 3D Shapes from an SVG Element
Learn how to create 3D shapes from SVG and explore THREE.ParametricGeometry.
We'll cover the following...
Use SVG to create 3D shapes
In THREE.ShapeGeometry, we mentioned that SVG follows pretty much the same approach to drawing shapes. In this lesson, we’ll look at how we can use SVG images together with THREE.SVGLoader to extrude SVG images. We’ll use the Batman logo as an example:
What is SVG?
SVG is an XML-based standard that can be used to create vector-based 2D images for the web. This is an open standard that is supported by all modern browsers. Directly working with SVG and manipulating it from JavaScript, however, isn’t very straightforward. Luckily, there are a couple of open source JavaScript libraries that make working with SVG a lot easier. Paper.js, Snap.js, D3.js, and Raphael.js are some of the best. If we want a graphical editor, we can also use the open-source Inkscape product.
Example: ExtrudeGeometry
Let’s execute the extrude-svg.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-6': './samples/chapters/chapter-6/extrude-svg.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',
}
}
Note: We can change the properties of the geometries from the right control panel in the output screen.
The THREE.SVGLoader
First, let’s look at what the original SVG code looks like:
Unless we’re an SVG guru, this probably won’t mean too much to us. Basically, what we see here is a set of drawing instructions. For instance on line 5, C 277.987 119.348 279.673 116.786 279.673 115.867 tells the browser to draw a cubic bezier curve, and L 489.242 111.787 tells us that we should draw a line to that specific position. ...