继承方法
threejs中通过 Object.assign方法向对象添加属性和方法等以实现继承。
WebGLRenderTarget
离屏渲染,是获取深度图,构建主渲染的必要方法。
也是实现后处理过程的核心方法。
function WebGLRenderTarget(width, height, options) {
this.width = width;
this.height = height;
this.scissor = new Vector4(0, 0, width, height);
this.scissorTest = false;
this.viewport = new Vector4(0, 0, width, height);
options = options || {};
this.texture = new Texture(undefined, options.mapping, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding);
this.texture.image = {};
this.texture.image.width = width;
this.texture.image.height = height;
this.texture.generateMipmaps = options.generateMipmaps !== undefined ? options.generateMipmaps : false;
this.texture.minFilter = options.minFilter !== undefined ? options.minFilter : LinearFilter;
this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : false;
this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
}
这是方法本身,给WebGLRenderTarget添加属性,相当于一个控制器。
接下来是添加内置方法
WebGLRenderTarget.prototype = Object.assign(Object.create(EventDispatcher.prototype), {
constructor: WebGLRenderTarget,
isWebGLRenderTarget: true,
setSize: function setSize(width, height) {
if (this.width !== width || this.height !== height) {
this.width = width;
this.height = height;
this.texture.image.width = width;
this.texture.image.height = height;
this.dispose();
}
this.viewport.set(0, 0, width, height);
this.scissor.set(0, 0, width, height);
},
clone: function clone() {
return new this.constructor().copy(this);
},
copy: function copy(source) {
this.width = source.width;
this.height = source.height;
this.viewport.copy(source.viewport);
this.texture = source.texture.clone();
this.depthBuffer = source.depthBuffer;
this.stencilBuffer = source.stencilBuffer;
this.depthTexture = source.depthTexture;
return this;
},
dispose: function dispose() {
this.dispatchEvent({
type: 'dispose'
});
}
});
可以看到,方法通过改变prototype的默认指向实现目的,同时第一行重新设置了constructor,因为在改变prototype指向的时候,constructor会发生一些奇怪的改变,具体可参考
EventDispatcher
着重解析一下其中的EventDispatcher。这是实现的一个类,是three.js的实体基类,主要负责监听和调度事件,具体注释可参考