react+three.js 设置背景颜色或图片
2019-08-12 本文已影响1人
不7而遇_
介绍两种方法来实现 在react项目中为three.js生成的内容设置背景
1.通过css设置canvas 的背景
new THREE.WebGLRenderer({canvas, alpha: true, antialias: true })
这里创建渲染器的方法第一个参数canvas 如果不传递的话,会在指定的 this.mount中自动生成一个canvas 如果指定了canvas会在指定的canvas 中渲染内容。在这里我们把要渲染的指定为 this.refs.pic
并且要设置 透明
alpha : true
在这里做一个提示,两个方法 写相对路径都无用,而且背景写内联样式才有效果
html
render() {
return (
<div
id= "canvas"
style={{ width: '600px', height: '600px' }}
ref={(mount) => { this.mount = mount }}
>
<canvas
ref = "pic"
className="pic"
style={{ background: 'linear-gradient(to right, #4590ad, #03163a )'}} //用渐变做背景
// style = {{background: 'url(https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1565586852696&di=10d15429d474cfbc812fa8a8430208ea&imgtype=0&src=http%3A%2F%2Fimg4q.duitang.com%2Fuploads%2Fitem%2F201305%2F08%2F20130508002211_CuPYn.jpeg)', backgroundSize: 'cover'}}//用 图片做背景
></canvas>
</div>
);
}
js
const canvas = this.refs.pic
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera( 75, this.mount.clientWidth / this.mount.clientHeight, 0.1, 1000 );
const renderer = new THREE.WebGLRenderer({canvas, alpha: true, antialias: true });
renderer.autoClearColor = false;
this.scene = scene
this.camera = camera
this.renderer = renderer
renderer.setSize(this.mount.clientWidth, this.mount.clientHeight );
this.mount.appendChild( renderer.domElement );
camera.position.set(0, 50, 0);
camera.up.set(0, 0, 1);
camera.lookAt(0, 0, 0);
//this.createLight()
//this.createStars()
//this.animate();
2.可以用three.js自带的方法来写
这里不需要指定canvas 。自动生成后设置sence背景就可以了,但是背景可能因为尺寸原因而变形
如果想改变形状可以参考three.js的官网或者 教程
html
<div
id= "canvas"
style={{ width: '600px', height: '600px' }}
ref={(mount) => { this.mount = mount }}
>
</div>
js
componentDidMount() {
console.log(this.refs)
this.init()
}
init = () => {
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera( 75, this.mount.clientWidth / this.mount.clientHeight, 0.1, 1000 );
const renderer = new THREE.WebGLRenderer({antialias: true });
renderer.autoClearColor = false;
this.scene = scene
this.camera = camera
this.renderer = renderer
renderer.setSize(this.mount.clientWidth, this.mount.clientHeight );
this.mount.appendChild( renderer.domElement );
camera.position.set(0, 50, 0);
camera.up.set(0, 0, 1);
camera.lookAt(0, 0, 0);
const loader = new THREE.TextureLoader();
const bgTexture = loader.load('../../assets/bg.jpg');
scene.background = bgTexture;
}