Intro to WebGL Using Angular- How to Set Up a Scene (Part 1)
文章推薦指數: 80 %
In this article, we're going to setup WebGL within a typical Angular app by utilising the HTML5 canvas ... The source code for this tutorial is available at ...
Skiptothecontent
CloseMenu
Whatwedo
Ourwork
Whoweare
Blog
GetinTouch
Overview
WebGL hastobeoneofthemostunder-usedJavaScriptAPIswithinmodernwebbrowsers.
Itoffersrenderinginteractive2Dand3Dgraphicsandisfullyintegratedwithotherwebstandards,allowingGPU-acceleratedusageofphysicsandimageprocessingeffectsaspartofthewebpagecanvas (Wikipedia,2020).
Inthisarticle,we’regoingtosetupWebGLwithinatypical Angular appbyutilisingthe HTML5canvaselement.
Prerequisites
Beforestarting,itsworthwhiletoensureyoursystemissetupwiththefollowing:
Nodejs isinstalledYouhave setup aneworexistingAngularappYouareusingamodernwebbrowser(Chrome56+,Firefox51+,Opera43+,Edge10240+)
WebGLFundamentals
There’shonestlyalottotakeinregardstothefundamentalsofWebGL(andmorespecificallyOpenGL).Itdoesmeanthatyou’llneedtohavesomebasicunderstandingoflinearalgebraand2d/3drenderingingeneral. WebGLFundamentals doesagreatjobatprovidinganintroductiontoWebGLfundamentalsandI’llbereferencingtheirdocumentationaswestepthroughsettingupourAngularapptouseWebGL.
Beforegoinganyfurther,itsimportantthatyouunderstandthefollowingataminimum.
WebGLis not a3DAPI.Youcan’tjustuseittoinstantlyrenderobjectsandmodelsandgetthemtodosomeawesomemagic.
WebGLisjusta rasterizationengine.Itdrawspoints,linesandtrianglesbasedonthecodeyousupply.
IfyouwantWebGLtodoanythingelse,itsuptoyoutowritecodethatusespoints,linesandtrianglestoaccomplishthetaskyouwant.
WebGLrunsontheGPUandrequiresthatyouprovidecodethatrunsontheGPU.Thecodethatweneedtoprovideisintheformofpairsoffunctions.
Theyareknownas:
avertexshaderresponsibleforcomputingvertexpositions–basedonthepositions,WebGLcanthenrasterizeprimitivesincludingpoints,lines,ortriangles.afragmentshaderwhenprimitivesarebeingrasterized,WebGLcallsthefragmentshadertocomputeacolourforeachpixeloftheprimitivethat’scurrentlybeingdrawn.
EachshaderiswritteninGLSLwhichisastrictlytypedC/C++likelanguage.Whenavertexandfragmentshaderarecombined,they’recollectivelyknownasa program.
NearlyalloftheentireWebGLAPIisaboutsettingupstateforthesepairsoffunctionstorun.Foreachthingyouwanttodraw,yousetupabunchofstatethenexecuteapairoffunctionsbycalling gl.drawArrays or gl.drawElements whichexecutesyourshadersontheGPU.
Anydatayouwantthosefunctionstohaveaccessto,mustbeprovidedtotheGPU.Thereare4waysashadercanreceivedata.
AttributesandbuffersBuffersarearraysofbinarydatayouuploadtotheGPU.Usuallybufferscontainthingslikepositions,normals,texturecoordinates,vertexcolours,etcalthoughyou’refreetoputanythingyouwantinthem.Attributesareusedtospecifyhowtopulldataoutofyourbuffersandprovidethemtoyourvertexshader.Forexampleyoumightputpositionsinabufferasthree32bitfloatsperposition.Youwouldtellaparticularattributewhichbuffertopullthepositionsoutof,whattypeofdataitshouldpullout(3component32bitfloatingpointnumbers),whatoffsetinthebufferthepositionsstart,andhowmanybytestogetfromonepositiontothenext.Buffersarenotrandomaccess.Insteadavertexshaderisexecutedaspecifiednumberoftimes.Eachtimeit’sexecutedthenextvaluefromeachspecifiedbufferispulledoutandassignedtoanattribute.UniformsUniformsareeffectivelyglobalvariablesyousetbeforeyouexecuteyourshaderprogram.TexturesTexturesarearraysofdatayoucanrandomlyaccessinyourshaderprogram.Themostcommonthingtoputinatextureisimagedatabuttexturesarejustdataandcanjustaseasilycontainsomethingotherthancolours.VaryingsVaryingsareawayforavertexshadertopassdatatoafragmentshader.Dependingonwhatisbeingrendered,points,lines,ortriangles,thevaluessetonavaryingbyavertexshaderwillbeinterpolatedwhileexecutingthefragmentshader.
(WebGLFundamentals,2015).
I’mglossingoveralotoftechnicaldetailhere,butifyoureallywanttoknowmore,headoverto WebGLFundamentalslessons formoreinfo.
Settingupaplayground
Let’ssetupaplaygroundsowehavesomethingthatwecanuseinordertocontinuesettingupWebGL.
First,createa component.YoucancreateonebyexecutingthefollowingcommandwithinyourAngularroot(src)directory.I’vegoneaheadandnamedmine scene.
E.g. nggeneratecomponentscene
PSX:\...\toucan-webgl>nggeneratecomponentscene
CREATEsrc/app/scene/scene.component.html(20bytes)
CREATEsrc/app/scene/scene.component.spec.ts(619bytes)
CREATEsrc/app/scene/scene.component.ts(272bytes)
CREATEsrc/app/scene/scene.component.scss(0bytes)
PSX:\...\toucan-webgl>
Let’s also create a service with the component and call it WebGL too.
E.g. nggenerateservicescene/services/webGL
PSX:\...\toucan-webgl>nggenerateservicescene/services/webGL
CREATEsrc/app/scene/services/web-gl.service.spec.ts(352bytes)
CREATEsrc/app/scene/services/web-gl.service.ts(134bytes)
PSX:\...\toucan-webgl>
Ifyou’reusinganewAngularapp,hopefullyyou’vealreadyconfiguredittouse AppRouting.Ifyouhaven’t,followthenextcoupleofsteps.
nggeneratemoduleapp-routing--flat--module=app
You’llnowhavean app-routing.module.ts file,ifyouhaven’tgotonealready.
Updatethecontentsofthefilewiththefollowing:
import{Routes,RouterModule}from"@angular/router";
import{SceneComponent}from"./scene/scene.component";
constroutes:Routes=[{path:"",component:SceneComponent}];
@NgModule({
imports:[RouterModule.forRoot(routes)],
exports:[RouterModule],
})
exportclassAppRoutingModule{}
Thiswillensurethatonappload,it’lldisplaythe SceneComponent first.
Next,addthe WebGLService tothe SceneComponent‘sconstructorlikeso:
import{Component,OnInit}from"@angular/core";
import{WebGLService}from"./services/web-gl.service";
@Component({
selector:"app-scene",
templateUrl:"./scene.component.html",
styleUrls:["./scene.component.scss"],
})
exportclassSceneComponentimplementsOnInit{
//***Updateconstructorhere***
constructor(privatewebglService:WebGLService){}
ngOnInit():void{}
}
Finally,run ngserve andchecktoseeiftheAngularappisrunninganddisplayingthe SceneComponent.Itshouldlooklikethis:
Now,letsmoveontoaddingaWebGLcontext.
SettinguptheWebGLcontext
SettinguptheWebGLcontextisalittlebitinvolvedbutoncewegetthefoundationgoingwecanthenproceedtostartgettingsomethingonthescreen.
Let’sstartbyopeningup scene.component.html andaddaHTML5canvaselement.
延伸文章資訊
- 1WebGL tutorial - Web APIs | MDN
WebGL programs 由JavaScript撰寫的指令碼以及透過電腦的Graphics Processing Unit (GPU)上運行的特殊效果程式碼(shader code)組成。W...
- 2WebGL Tutorial - Tutorialspoint
WebGL Tutorial, WebGL (Web Graphics Library) is the new standard for 3D graphics on the Web, desi...
- 3WebGL Fundamentals
Modern WebGL tutorials that teach WebGL from basic principles. ... and bringing you to a full und...
- 4Learn WebGL — LearnWebGL
These tutorials start with the “big picture” and then study the details of each ... Therefore, wh...
- 5Day 9 : WebGL初探 - iT 邦幫忙
WebGL又是基於OpenGL ES而發展的函式庫,所以可以說只要是OpenGL 2.0版本運行ok的程式碼,應該就 ... WebGL 是JavaScript API, 內容都寫在HTML5 ...