首先我的html结构如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Demo</title>
</head>
<body>
<canvas class="webgl"></canvas>
</body>
</html>
Three.js设置透明背景步骤如下:
1.为body添加背景图
body {
margin: 0;
overflow: hidden;
background-image: url('../static/53d69d934eb64.jpg');
background-size: cover;
background-repeat: repeat;
background-position: center center;
}
2.webgl(即three.js的canvas)设置为透明(背景图放在这一层也可以)
.webgl {
position: fixed;
top: 0;
left: 0;
outline: none;
background-color: transparent;
}
3.代码中设置renderer允许透明
const renderer = new THREE.WebGLRenderer({
canvas: canvas,
antialias: true,
alpha: true
})
设置完成后three.js部分就可以显示在背景图上啦: