Is there any reason for using WebGL instead of 2D Canvas for ...

文章推薦指數: 80 %
投票人數:10人

Both canvas and webGL are JavaScript APIs. They are pretty much the same regarding integration (binding). They are both supported by a ... Home Public Questions Tags Users Collectives ExploreCollectives FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore IsthereanyreasonforusingWebGLinsteadof2DCanvasfor2Dgames/apps? AskQuestion Asked 8years,1monthago Active 1monthago Viewed 97ktimes 143 35 Isthereanyreason,exceptperformance,forusingWebGLinsteadof2D-Canvasfor2Dgames/apps? Inotherwordwhat2DfunctionalitiesareofferedbyWebGLwhicharenotpossibletoachieveeasilywith2D-Canvas? htmlhtml5-canvaswebgl Share Improvethisquestion Follow editedFeb8,2014at12:48 AliShakiba askedFeb6,2014at12:43 AliShakibaAliShakiba 19.4k1717goldbadges6060silverbadges8787bronzebadges 2 11 Bytheway:Whileyoucan'tusethe2dandthe3dcontextAPIonthesamecanvas,youcanstillcombinethembyusingmultiplecanvases.WebGLcanuse2dcanvasesastexturesand2dcanvasescanuseWebGLcanvasesassourcesfordrawImage. – Philipp Feb7,2014at8:26 1 Forafewmoredetailson@Philipp'scommentseethisQ/A. – bluenote10 Jun13,2021at20:04 Addacomment  |  9Answers 9 Sortedby: HighestScore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 119 Lookingatthisquestionfromanotherside: howdoesadeveloperchooseonetechnologyoveranother? integratesbetterintheiralreadybuiltsystem iseasiertouse isfaster hasmorecapabilitiesorbettersuitstheirneeds cost moreplatfrom-independant SoI'lldiscussthedifferencesbetweencanvasandwebGLAPIsregardingthesequalities. BothcanvasandwebGLareJavaScriptAPIs.Theyareprettymuchthesameregardingintegration(binding).Theyarebothsupportedbyanumberoflibrariesthatcouldspeedupyourcoding.Differentlibrariesgiveyoudifferentwaystoorganizeyourcode,solibrarychoicedictateshowyourdrawingAPIsarestructured,butit'sstillprettymuchthesamething(howtherestofthecodebindstogetherwithit).Ifyouuselibrary,theeaseofwritingcodedependsonthelibraryitself. Ifyouwritecodefromzero,thecanvasAPIismucheasiertolearnandunderstand.Itrequiresminimalmathknowledge,anddevelopmentisfastandstraightforward. WorkingwiththeWebGLAPIrequiresstrongmathskillsandafullunderstandingoftherenderingpipeline.Peoplewiththeseskillsarehardertofind,productionisslower(duetothesizeandcomplexityofsuchacodebase),andthereforeitcostsmore. WebGLisfasterandithasmorecapabilities.Nodoubtaboutthat.It'sanative3DAPIthatgivesyoufullaccesstotherenderingpipeline,codeandeffectsareexecutedfasterandaremore'tweakable'.WithwebGLtherereallyisnolimit. BothcanvasandwebGLarehtml5goodies.Usuallythedevicesthatsupportonewillsupportandtheother. So,tosumup: mergingthedrawingAPIcodeandtherest(integration):similar easeofuse: (withlibrary)canvas=webGL (fromscratch)webGL<canvas capabilities:webGL>canvas cost:webGLismuchmoreexpensive platform:verysimilar Hopethishelps. P.S.Openfordiscussion. Share Improvethisanswer Follow editedSep25,2019at7:47 ZachSmith 7,5841010goldbadges4646silverbadges107107bronzebadges answeredFeb8,2014at23:41 DraganOkanovicDraganOkanovic 6,88133goldbadges3030silverbadges4343bronzebadges 6 @Abstract,WherearegoodtutorialsforwebGLandhowmanyhourswillittake? – Pacerier Oct19,2017at4:46 1 @Pacerierjustgoogleit,firstfewhitsareprobablygoodenough.However,itwilltakeweeksandmonthstogetgoodatwebglandgraphicsprogrammingingeneral,andyearstobereallygood.It'snotjustsomerandom"library"thatyouneedtolearnAPIforandthat'sit. – DraganOkanovic Oct19,2017at10:14 @AbstractAlgorithm,Imeanifyou'realramasterwithprogrammingcanvas,howmanyhourswillswitchingtowebGLtake? – Pacerier Oct22,2017at16:52 @PacerierthatdependsonthedevandasAbstractalreadysaidthemathskillsofthedevinvolved.Therereallyisn'taquantificationthatcanbemade. – scrappedcola Oct23,2017at12:43 thanksforthiscomparison.anyupdatesin2021,ordoyoubelievethisanalysisstillholds? – Crashalot Jan5,2021at23:23  |  Show1morecomment 37 Thebiggestadvantageistheprogrammabilityofthepipeline,andtheperformance.Forexample,sayyouaredrawing2boxesoneaboveotherandoneishidden,someGLimplementationshavescopefordiscardingthehiddenbox. Asforcomparisons,Sincethereisnoquickwayofcreatingatablehere,Ijustuploadedapictureofthecomparisontablebelow.AddedThree.jsforcompletenessonly. Share Improvethisanswer Follow answeredFeb9,2014at13:51 PrabindhPrabindh 3,19022goldbadges2121silverbadges2424bronzebadges 1 Re"someGLimplementationshavescopefordiscardingthehiddenbox"butcouldn'tyoudetectthatoverriddenpartinJSandthusnotredrawwhat'snotneeded? – Pacerier Oct19,2017at4:47 Addacomment  |  21 +25 Speakingfromexperienceonmyownapplications,graphicsshadershavebeentheoneandonlyreasonI'verequiredsupportforWebGL.Easeofusehaslittlebearingformesincebothframeworkscanbeabstractedawaywiththree.js.AssumingIdon'tneedshaders,Iallowuseofeitherframeworktomaximizebrowser/machinesupport. Share Improvethisanswer Follow editedFeb11,2014at17:00 answeredFeb11,2014at16:16 1680716807 1,34022goldbadges1616silverbadges3232bronzebadges 0 Addacomment  |  18 What2DcapabilitydoesWebGLofferthat2Dcanvasdoesnot?ThebiggestoneIMHOistheprogrammablefragmentshadersonthegraphicshardware.Forexample,inWebGL,onecanimplementConway'sGameofLifeinashaderonyour3Dhardware: http://glslsandbox.com/e#207.3 Thiskindof2DdisplaywouldonlyrunontheCPU,nottheGPU,witha2Dcanvas.AllofthecomputationswouldbeimplementedinJavaScript,andwouldnotbeasparallelastheGPUevenwiththehelpofwebworkers.Thisisjustoneexampleofcourse,allkindsofinteresting2Deffectscanbeimplementedwithshaders. Share Improvethisanswer Follow editedJun22,2015at15:13 answeredFeb12,2014at18:27 emackeyemackey 10.6k22goldbadges3232silverbadges5252bronzebadges 3 2 Thusvscanvas,isWebGLmoreorlesstaxingontheOS? – Pacerier Oct19,2017at4:48 I'mcuriouswhetherallcanvasendsupdoingwebglanyway;ifitusesprecompiledcommonusecasewebgl,whichwouldbemoreefficientthandirectwebgl;orifit'snotinterfacingwithopenglinanywayunlessyouusewebgl. – Dmitry Oct29,2017at15:25 1 @Dmitrygreatquestion,anddifferentbrowsersarefreetotakedifferentapproachestothatproblem.But,nomatterhowtheyacceleratetheCanvas2DAPI,theCanvas2DAPIitselfdoesn'tofferprogrammableshadersorvertexarraybuffers.It'sa"chatty"API(oneJavaScript-to-Nativecallperelementdrawn),whereasWebGL'sAPIallowsbulkdataloadingandGPU-basedcustomprocessing. – emackey Oct30,2017at13:31 Addacomment  |  16 Well,performancewouldbetheoneofthebiggestreasonsbecausewhenyouarecodingagame,ithastobefast.ButthereareacoupleofotherreasonsforwhichyoumightwanttochooseWebGLovercanvas.Itoffersthepossibilitytocodingshaders,lightingandzooming,whichisimportantifyouaredoingacommercialgameapp.Alsocanvasgetslaggyafter50spritesorso. Share Improvethisanswer Follow editedOct7,2015at11:08 answeredFeb6,2014at12:50 Xk0nSidXk0nSid 89122goldbadges99silverbadges1919bronzebadges 5 1 EspeciallyonadevicelikeanandroidtabletwheretheCPUgetsoverloadedquickinjavascript,themainreasontouseWebGListotransfertherenderingloadontotheGPU. – Curtis Jun30,2017at21:20 1 @Xk0n,Re"fersthepossibilitytocodingshaders,lightingandzooming",Butthendoesn'titbecomeGPU-dependent? – Pacerier Oct19,2017at4:49 YoucanstillzoomwithsetTransformina2Dcanvascontext.I'vebeenhavingahardtimewithtexturebleedingin2Dcanvaswhenscalingfromspritesheets,however,whichiswhyI'mturningtoWebGL.Isawatutorialthatstopsthenearestneighborsamplingfromgoingoutsideofthesourcerect,whichshouldfixmybleedingedgeproblem. – Frank Feb22,2020at13:53 After50?Yikes,Iwasabouttodotensofthousandsoftiles... – Pangamma Mar22,2021at21:38 @Xk0nSidcanyoupleaseexpandon"Alsocanvasgetslaggyafter50spritesorso."doyouhavealinktobackthisup? – AlexisTyler May9,2021at10:11 Addacomment  |  9 There'snothingyoucandowithCanvasyoucan'tdowithwebGL:thecanvasallowstocrushthebyteswithget/putImageData,andyoumightdrawlines,circles,...programmaticallywithwebGL. Butifyou'reseekingtodoquitesomedrawings,andalsosomeeffectsat60fps,theperformancegapissohighthatitjustwon'tbepossiblewithcanvas,whenitwillrunokinwebGL.Performanceisarootfeature. YetwebGLisquitecomplicatedtoprogram:seeifcanvasisgoodenoughforyouorseekalibrarythatwilleasethepain... Otherdrawback:itdoesn'tworkonIE(butwhatdoes?),andonsomemobiles. Seehereforcompatibility:http://caniuse.com/webgl Share Improvethisanswer Follow answeredFeb6,2014at13:26 GameAlchemistGameAlchemist 18.3k77goldbadges3434silverbadges5656bronzebadges 1 1 anyupdatesonthisopinionfor2021(besideswidespreadcompatibilityforwebglnow)?thanksforsharing! – Crashalot Jan5,2021at23:30 Addacomment  |  8 Asyouspecificallywantsomeclassic2dthingsthatdon'tworkwellwithcanvas: colortransforms(likeblinkingasprite) repeatingbitmapfills tilingmapsunderrotation(undercanvassomeimplementationswillcreateseams) deeplayering(veryimplementationdependent) multiplicativeoradditiveblending ...butofcourseyouhavepixelaccess,soyoucandoreallyanything,includingtheabove,manually.Butthatcanbereally,reallyslow.YoucouldemscriptenMesaopenGltorendertocanvasintheory. AnotherbigreasontousewebGLwouldbethattheresultisveryeasytoporttoanywhereelse.Whichalsomakestheskillmorevaluable. Reasonstousecanvasarethatitisstillbettersupportedandifyoulearndoingthingspixelbypixelthatisalsoaveryvaluablelesson. Share Improvethisanswer Follow answeredFeb14,2014at5:56 starmolestarmole 4,7882424silverbadges4747bronzebadges 3 BtwIsWebGLmultithreaded?Canyouhavetwothreadsdrawingtwopartsofthescreenconcurrently? – Pacerier Oct19,2017at4:53 Ithinkthattheansweris"yesandno,"sincewebbrowsersareinherentlysingle-threaded,socopyingthedatatoberenderedtotheGPUisnotmulti-threaded.But,youareusingthemassiveparallelizationofthegraphicscardoncetheshadersstartrendering,whichisessentiallydrawingtomultiplepartsofthescreenatonce.PleasecorrectmeifI'mwrong,anyone. – KentWeigel Feb19,2020at0:31 thanksforsharing.doyouthinkthisanalysisisstilltruein2021? – Crashalot Jan5,2021at23:26 Addacomment  |  4 WebGLisunusablewithoutaGPU. ThishardwaredependencyisnotabigproblembecausemostsystemshaveGPUs,butifGPUorCPUarchitectureseverevolve,preservingwebglcontentbyemulationmaybechallenging.Runningitonold(virtualized)computersisproblematic. But"CanvasvsWebGL"doesnothavetobeabinarychoice. Iactuallypreferusingwebglforeffects,butdoingtherestincanvas. WhenIrunitinaVM,itstillworksnicelyandfast,justwithouttheeffects. Update:Unfortunatellysomebrowsers(ChromeonWindows,EverythingonLinux,others?)implementwell-meantemulationlayersthatmakedetectionofpoor/noGPUshard.InthesecaseseitherthegameortheuserhastodisableWebGLmanuallytogettheactualperformancebenefits... ...ordegradation,whenthe2Disimplementedpoorly.Allegedlythatcanhappentoo.[Thanksgman] Share Improvethisanswer Follow editedDec7,2020at17:04 answeredMar27,2020at10:24 user185953user185953 7566bronzebadges 3 Thisisuntrue.ChromehasrunWebGLinsoftwareonsystemswithoutGPUforthelast8years. – gman Nov26,2020at5:17 Quotingthepage:"TheperformanceofSwiftShadershouldbegoodenoughtoviewsimple3Dcontent"."Working",butunusableforgames.@gman – user185953 Dec2,2020at14:53 Correct,butthis"WebGLisunusablewithoutaGPU"isfalse.Itmightbeslowbutitisnotunusable.ifitwasunusablewithoutaGPUtherewouldbenoreasonforasolutiontouseitwithoutaGPUtoevenexistinChrome. – gman Dec2,2020at17:41 Addacomment  |  3 AsWebGLisparticularlynewtechnologyandHTML5canvasismoreestablishedwhatyouwanttousedependsonyourusers.IfyouthinkthatyouruserswillusemobiledevicesthenIwouldsuggestHTML5canvasbutifyouwantbetter2DrenderingIwoulduseWebGL.SowhatyoucoulddoisiftheuseisonmobilerenderwithHTML5elseiftheyareonaplatformthatsupportsWebGL. Forexample: if(window.WebGLRenderingContext){ webGLcanvasApp() }elseif(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent)){ html5CanvasAppFMobile() }else{ html5CanvasApp() } Sources: ProperwaytodetectWebGLsupport? WhatisthebestwaytodetectamobiledeviceinjQuery? Share Improvethisanswer Follow editedMay8,2018at13:51 answeredFeb14,2014at20:58 brenbren 4,05433goldbadges2424silverbadges4141bronzebadges 0 Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedhtmlhtml5-canvaswebgloraskyourownquestion. TheOverflowBlog Stopaggregatingawaythesignalinyourdata FeaturedonMeta StackExchangeQ&AaccesswillnotberestrictedinRussia PlannedmaintenancescheduledforFriday,March18th,00:30-2:00UTC... Improvingthefirst-timeaskerexperience-Whatwasaskingyourfirst... Linked 1853 Whatisthebestwaytodetectamobiledevice? 55 ProperwaytodetectWebGLsupport? 22 Canvas3Ddrawingusingboth2Dand3Dcontext 6 DetectSwiftShaderWebGLrendererinChrome18 Related 2420 Makeadivfilltheheightoftheremainingscreenspace 1802



請為這篇文章評分?