JavaScript webgl framebuffer object | Develop Paper
文章推薦指數: 80 %
By default, the final drawing result of webgl is stored in the color buffer, and the frame buffer object can be used to replace the color ...
Position:Home>Program>Content
JavaScriptwebglframebufferobject
Time:2022-2-14
Introduction
WatchingHowIbuiltawindmapwithWebGLWhenIusedtheframebuffer,Icheckedthedataandtrieditalone.
Origin
MyGitHub
Framebufferobject
WebglhastheabilitytousetherenderingresultsastexturesFramebufferobject(framebufferobject)。
Bydefault,thefinaldrawingresultofwebglisstoredinthecolorbuffer,andtheframebufferobjectcanbeusedtoreplacethecolorbuffer.Asshowninthefigurebelow,theobjectdrawnintheframebufferwillnotbedirectlydisplayedoncanvas,sothistechnologyisalsoknownasOffscreendrawing(offscreendrawing)。
Examples
Inordertoverifytheabovefunctions,thisExamplesApicturewillbedrawnintheframebuffer,andthenitwillbedrawnanddisplayedagainasatexture.
bebasedonUsepictureexampleThelogicofismainlychangedinthefollowingaspects:
data
Framebufferobject
draw
data
Paintingintheframebufferisthesameasnormalpainting,butitisnotdisplayed,sothereshouldalsobecorrespondingpaintingareasize,vertexcoordinatesandtexturecoordinates.
Offscreenwidth:200,//widthdrawnoffscreen
Offscreenheight:150,//theheightdrawnfromthescreen
//Partialcodeomission
//Vertexandtexturecoordinatespaintedagainsttheframebuffer
this.offScreenBuffer=this.initBuffersForFramebuffer(gl);
//Partialcodeomission
initBuffersForFramebuffer:function(gl){
constvertices=newFloat32Array([
0.5,0.5,-0.5,0.5,-0.5,-0.5,0.5,-0.5,
]);//rectangle
constindices=newUint16Array([0,1,2,0,2,3]);
consttexCoords=newFloat32Array([
1.0,
1.0,//upperrightcorner
0.0,
1.0,//upperleftcorner
0.0,
0.0,//lowerleftcorner
1.0,
0.0,//lowerrightcorner
]);
constobj={};
obj.verticesBuffer=this.createBuffer(gl,gl.ARRAY_BUFFER,vertices);
obj.indexBuffer=this.createBuffer(gl,gl.ELEMENT_ARRAY_BUFFER,indices);
obj.texCoordsBuffer=this.createBuffer(gl,gl.ARRAY_BUFFER,texCoords);
returnobj;
},
createBuffer:function(gl,type,data){
constbuffer=gl.createBuffer();
gl.bindBuffer(type,buffer);
gl.bufferData(type,data,gl.STATIC_DRAW);
gl.bindBuffer(type,null);
returnbuffer;
}
//Partialcodeomission
Vertexshadersandsliceshaderscanbenewlydefined.Here,asetissharedforconvenience.
Framebufferobject
Todrawintheframebuffer,youneedtocreatethecorrespondingframebufferobject.
//Framebufferobject
this.framebufferObj=this.createFramebufferObject(gl);
//Partialcodeomission
createFramebufferObject:function(gl){
letframebuffer=gl.createFramebuffer();
lettexture=gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D,texture);
gl.texImage2D(
gl.TEXTURE_2D,
0,
gl.RGBA,
this.offscreenWidth,
this.offscreenHeight,
0,
gl.RGBA,
gl.UNSIGNED_BYTE,
null
);
//Reversethey-axisdirectionofthepicture
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,true);
//Texturecoordinateshorizontalfills
gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,gl.CLAMP_TO_EDGE);
//Texturecoordinatesverticalfillt
gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,gl.CLAMP_TO_EDGE);
//Textureamplificationprocessing
gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,gl.LINEAR);
//Texturereductionprocessing
gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,gl.LINEAR);
framebuffer.texture=texture;//Savetextureobject
//Associatebufferobject
gl.bindFramebuffer(gl.FRAMEBUFFER,framebuffer);
gl.framebufferTexture2D(
gl.FRAMEBUFFER,
gl.COLOR_ATTACHMENT0,
gl.TEXTURE_2D,
texture,
0
);
//Checkwhethertheconfigurationiscorrect
vare=gl.checkFramebufferStatus(gl.FRAMEBUFFER);
if(gl.FRAMEBUFFER_COMPLETE!==e){
console.log("Framebufferobjectisincomplete:"+e.toString());
return;
}
gl.bindFramebuffer(gl.FRAMEBUFFER,null);
gl.bindTexture(gl.TEXTURE_2D,null);
returnframebuffer;
}
//Partialcodeomission
createFramebufferFunctiontocreateaframebufferobject.ThefunctiontodeletetheobjectisdeleteFramebuffer。
Aftercreation,youneedtoassignthecolorassociationobjectoftheframebuffertoatextureobject.Thetextureobjectcreatedintheexamplehasseveralcharacteristics:1.Thewidthandheightofthetextureareconsistentwiththewidthandheightofthedrawingarea;2usetexImage2DThelastparameterisnullThatis,ablankareaforstoringtextureobjectsisreserved;3thecreatedtextureobjectisplacedontheframebufferobject,whichisthislineofcodeframebuffer.texture=texture。
bindFramebufferFunctiontobindtheframebuffertothetarget,andthenuseframebufferTexture2DBindthepreviouslycreatedtextureobjecttothecolorassociationobjectoftheframebuffergl.COLOR_ATTACHMENT0Comeon.
checkFramebufferStatusCheckwhethertheframebufferobjectisconfiguredcorrectly.
draw
Themaindifferenceindrawingistheswitchingprocess:
//Partialcodeomission
draw:function(){
constgl=this.gl;
constframeBuffer=this.framebufferObj;
this.canvasObj.clear();
constprogram=this.shaderProgram;
gl.useProgram(program.program);
//Thismakesthetargetofpaintingbecomeaframebuffer
gl.bindFramebuffer(gl.FRAMEBUFFER,frameBuffer);
gl.viewport(0,0,this.offscreenWidth,this.offscreenHeight);
this.drawOffFrame(program,this.imgTexture);
//Whentheframebufferisunbound,thepaintedtargetbecomesacolorbuffer
gl.bindFramebuffer(gl.FRAMEBUFFER,null);
gl.viewport(0,0,gl.canvas.width,gl.canvas.height);
this.drawScreen(program,frameBuffer.texture);
},
//Partialcodeomission
UsefirstbindFramebufferToturnthepaintedtargetintoaframebuffer,youneedtospecifythecorrespondingviewport.
Aftertheframebufferisdrawn,unbindandreturntothenormaldefaultcolorbuffer.Youalsoneedtospecifythecorrespondingviewport,especiallythetextureofthebufferobject,whichindicatesthatitisthedrawingresultobtainedfromtheframebuffer.
Observationandthinking
TherelevantexamplesfoundontheInternetfeelcomplex.Thefollowingobservationsandthoughtsaremadeintheprocessoftryingtosimplify.
framebuffer.textureIsitaninherentattributeoranartificialaddition?
Thislogicisusedwhencreatingframebufferobjects:framebuffer.texture=texture,thentheframebufferobjectitselfhastextureAttribute?
Itisfoundthatthisattributewasnotfoundwhenthelogwasfirstcreated,soitisspeculatedthatitshouldbeaddedartificially.
framebuffer.textureWhenistherecontent?
Wheninitializingtheframebufferobject,thestoredtextureisblank,butfromthefinalresult,aftertheframebufferisdrawn,thetexturehascontent,soframebuffer.textureWhendidtheattributehavecontent?
Inthedrawinglogic,thestatementsrelatedtotextureare:
gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D,texture);
gl.uniform1i(program.uSampler,0);
gl.drawElements(gl.TRIANGLES,6,gl.UNSIGNED_SHORT,0);
Presumablygl.drawElementsMethodtodrawthecolorassociationobjectwhoseresultisstoredintheframebuffer,andthecolorassociationobjectoftheframebufferisassociatedwiththecreatedblanktextureobjectduringinitialization,framebuffer.textureItalsopointstothesameblanktextureobject,sothereiscontentintheend.
Whydidn’tthefinaldisplaycoverthewholecanvas?
Whenyoufinallypaintthedisplayablecontent,youcanfindthattheverticescorrespondtothewholecanvasandthetexturecoordinatescorrespondtothewholetexture,butwhynotspreadthewholecanvas?
Thetextureusedinthefinalrenderingofdisplayablecontentcomesfromtherenderingresultoftheframebuffer,andtheverticesoftheframebuffercorrespondtohalfofthewholebuffer.Iftherenderingresultofthewholeframebufferisregardedasatextureandscaledaccordingtothescaleofthefinalrenderingvisualarea,thefinalrenderingisnotcovered,whichistheexpectedcorrectresult.
ThisiscoveredwithcanvasExamples,simplyadjustthebufferverticestocorrespondtotheentirebuffersize.
referencematerial
Webglprogrammingguideframebufferexample
WebGLFramebuffers
WebGLdisplayframebuffer?
Tags:Buffer,Draw,Examples,object,texture
RecommendedToday
[vue3+vite+TS]3.0componentII:iconselector
PrerequisiteUIcomponentsTheiconselectorwillusethefollowingcomponents:IconiconButtonbuttonMessagepromptDialogdialogComponentdesignModifyrouteSRC\router\indexts/**@Author:bobokaka*@Date:2021-12-1911:26:38*@LastEditTime:2021-12-2021:17:12*@LastEditors:bobokaka*@Description:route*@FilePath:\vue3-element-ui-baseline\src\router\index.ts*/import{createRouter,createWebHistory,RouteRecordRaw}from‘vue-router’[…]
Frontendinterviewdaily3+1–day1012
Openplatform:briefintroduction
UnderstandRedux
[algorithm]askandanswerwhyandhowtolearnalgorithms
HowcanTaobaotmallAPIobtainproductdetails|SKU|price|store|coupon|freightinformation
Let’stalkabouthowtoregisterthird-partyservicesintothespringcontainerofourproject
Writeatodolistcasewithpurereacthooks(1)
Vuedevelopmentenvironmentinstallation(NVMmanagementnode)
Styluscombinedwithweuisourcecodecomponentanalysisnotes
OnJSresourcesubcontracting
Pre:Thedifferencebetweenschemasandmodelsinfastapi
Next:[January26,2022]recyclerviewpull-upandpull-down
Searchfor:
Tagsaddress
algorithm
array
assembly
attribute
Browser
c
Catalog
Characterstring
Client
code
command
configurationfile
container
data
Database
Definition
Edition
element
Example
file
function
java
javascript
Journal
link
linux
Memory
method
Modular
mysql
node
object
page
parameter
php
Plug-inunit
project
python
Route
sourcecode
Theserver
Thread
time
user
RecentPosts
[vue3+vite+TS]3.0componentII:iconselector
2021impressedmedeeply&wonderfulbug/defect/problemrecord
MySQLexecutionprocessandorder
Bye,swagger!Usesmartdoctogenerateinterfacedocumentswithoutintrusion
LetAndroidstudiosimulator(AVD)accesstheInternet
RecentCommentswangdaionAnswerfor”Thestrangephenomenonof"danglingpointer"!!There'salivingmanthereonAnswerfor”Thestrangephenomenonof"danglingpointer"!!wangdaionAnswerfor”Thestrangephenomenonof"danglingpointer"!!big_CIAonAnswerfor”Thestrangephenomenonof"danglingpointer"!!There'salivingmanthereonAnswerfor”Thestrangephenomenonof"danglingpointer"!!Categories
.NETCore
AgileDevelopment
AlgorithmAndDataStructure
Android
AppleMAC
ArchitectureDesign
ArtificialIntelligence
ASP.NET
Backend
Blockchain
C
C#
C++
Cloud
Database
DesignPattern
DevelopmentTool
Embedded
Erlang
Freshman
Game
Golang
HTML/CSS
HTML5
InformalEssay
InformationSecurity
IOS
Java
JavaScript
JSP
Linux
Lua
MongoDB
MsSql
MySql
NetworkSecurity
OOP
oracle
OtherDB
OtherTechnologies
OtherTechnology
Perl
PHP
Program
Python
Redis
RegularExpression
Ruby
Rust
SAP
Server
SoftwareTesting
TeamManagement
VBS
VUE
WEBFrontEnd
Windows
XML/XSLT
java
php
python
linux
windows
android
ios
mysql
html
.net
github
node.js
Copyright©2022DevelopPaperAllRightsReserved
Sitemap AboutDevelopPaper PrivacyPolicy ContactUs
延伸文章資訊
- 1一起幫忙解決難題,拯救IT 人的一天
Framebuffer. 如何在網頁中繪製3D 場景?從WebGL 的基礎開始說起系列第22 篇. PastLeo. 7 個月前‧ 283 瀏覽. 0. 大家好,我是西瓜,你現在看到的是2021...
- 2JavaScript WebGL framebuffer object - SegmentFault 思否
When How I built a wind map with WebGL , framebuffer was used in it, so I checked the data and tr...
- 3WebGL中图片多级处理(FrameBuffer) - 纸异兽- 博客园
FBO(Frame Buffer Object)是被推荐用于将数据渲染到纹理对象的扩展。 FrameBuffer就像是一个webgl显示容器一样,平时我们使用gl.drawArrays或者gl.
- 4WebGLRenderingContext.bindFramebuffer() - Web APIs | MDN
Binding a frame buffer. var canvas = document.getElementById('canvas'); var gl = canvas.getContex...
- 5WebGL基础学习篇(Lesson 8) - GitHub
这个方法更易于实现而且也更利于大家了解选取的工作原理。 最基础的思想就是将每个物体都渲染成不同的颜色,并且将场景渲染到offscreen framebuffer中。接着,当用户 ...