HTMLCanvasElement.getContext() - Web APIs | MDN

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

Note: The identifier "experimental-webgl" is used in new implementations of WebGL. These implementations have either not reached test suite ... SkiptomaincontentSkiptoselectlanguageReferencesWebAPIsHTMLCanvasElementHTMLCanvasElement.getContext()ArticleActionsEnglish(US)SyntaxExamplesSpecificationsBrowsercompatibilitySeealsoRelatedTopicsCanvasAPIHTMLCanvasElementPropertiesheight mozOpaquewidthMethods captureStream()getContext() mozFetchAsStream() mozGetAsFile()toBlob()toDataURL() transferControlToOffscreen()EventswebglcontextlostInheritance:HTMLElementElementNodeEventTargetRelatedpagesforCanvasAPICanvasCanvasGradientCanvasImageSourceCanvasPatternCanvasRenderingContext2DImageBitmapImageBitmapFactoriesImageBitmapRenderingContextImageDataOffscreenCanvasPath2DTextMetricsSyntaxExamplesSpecificationsBrowsercompatibilitySeealsoHTMLCanvasElement.getContext() The HTMLCanvasElement.getContext()methodreturnsadrawing contextonthecanvas,ornullifthecontextidentifierisnot supported,orthecanvashasalreadybeensettoadifferentcontextmode. Latercallstothismethodonthesamecanvaselement,withthesame contextTypeargument,willalwaysreturnthesamedrawingcontextinstance aswasreturnedthefirsttimethemethodwasinvoked.Itisnotpossibletogeta differentdrawingcontextobjectonagivencanvaselement. Syntaxvarctx=canvas.getContext(contextType); varctx=canvas.getContext(contextType,contextAttributes); Parameters contextType IsaDOMStringcontainingthecontextidentifierdefiningthedrawing contextassociatedtothecanvas.Possiblevaluesare: "2d",leadingtothecreationofa CanvasRenderingContext2Dobjectrepresentingatwo-dimensional renderingcontext. "webgl"(or"experimental-webgl")whichwillcreatea WebGLRenderingContextobjectrepresentingathree-dimensional renderingcontext.ThiscontextisonlyavailableonbrowsersthatimplementWebGLversion1(OpenGLES2.0). "webgl2"whichwillcreateaWebGL2RenderingContext objectrepresentingathree-dimensionalrenderingcontext.Thiscontextisonly availableonbrowsersthatimplementWebGL version2(OpenGLES3.0). "bitmaprenderer"whichwillcreatean ImageBitmapRenderingContextwhichonlyprovidesfunctionalityto replacethecontentofthecanvaswithagivenImageBitmap. Note:Theidentifier"experimental-webgl"isused innewimplementationsofWebGL.Theseimplementationshaveeithernotreached testsuiteconformance,orthegraphicsdriversontheplatformarenotyet stable.TheKhronosGroupcertifiesWebGL implementationsundercertainconformance rules. contextAttributes Youcanuseseveralcontextattributeswhencreatingyourrenderingcontext,for example: constgl=canvas.getContext('webgl',{ antialias:false, depth:false }); 2dcontextattributes: alpha:Booleanthatindicatesifthecanvas containsanalphachannel.Ifsettofalse,thebrowsernowknows thatthebackdropisalwaysopaque,whichcanspeedupdrawingoftransparent contentandimages. desynchronized:Booleanthathintstheuseragent toreducethelatencybydesynchronizingthecanvaspaintcyclefromtheevent loop (Geckoonly) willReadFrequently:Booleanthatindicateswhether ornotalotofread-backoperationsareplanned.Thiswillforcetheuseofa software(insteadofhardwareaccelerated)2Dcanvasandcansavememorywhen callinggetImageData() frequently.Thisoptionisonlyavailable,iftheflag gfx.canvas.willReadFrequently.enableissettotrue (which,bydefault,isonlythecaseforB2G/FirefoxOS). (Blinkonly)storage: Stringthatindicateswhichstorageisused("persistent"bydefault). WebGLcontextattributes: alpha:Booleanthatindicatesifthecanvas containsanalphabuffer. depth:Booleanthatindicatesthatthedrawing bufferisrequestedtohaveadepthbufferofatleast16bits. stencil:Booleanthatindicatesthatthedrawing bufferisrequestedtohaveastencilbufferofatleast8bits. desynchronized:Booleanthathintstheuseragent toreducethelatencybydesynchronizingthecanvaspaintcyclefromtheevent loop antialias:Booleanthatindicateswhetherornot toperformanti-aliasingifpossible. failIfMajorPerformanceCaveat:Booleanthat indicatesifacontextwillbecreatedifthesystemperformanceisloworifno hardwareGPUisavailable. powerPreference:Ahinttotheuseragent indicatingwhatconfigurationofGPUissuitablefortheWebGLcontext.Possible valuesare: "default":LettheuseragentdecidewhichGPUconfigurationis mostsuitable.Thisisthedefaultvalue. "high-performance":Prioritizesrenderingperformanceover powerconsumption. "low-power":Prioritizespowersavingoverrendering performance. premultipliedAlpha:Booleanthatindicatesthat thepagecompositorwillassumethedrawingbuffercontainscolorswith pre-multipliedalpha. preserveDrawingBuffer:Ifthevalueistruethe bufferswillnotbeclearedandwillpreservetheirvaluesuntilclearedor overwrittenbytheauthor. xrCompatible:Booleanthathintstotheuseragent touseacompatiblegraphicsadapterforan immersiveXRdevice.Settingthis synchronousflagatcontextcreationisdiscouraged;rathercalltheasynchronous WebGLRenderingContext.makeXRCompatible()methodthemomentyou intendtostartanXRsession. ReturnvalueArenderingcontextwhichiseithera CanvasRenderingContext2Dfor"2d", WebGLRenderingContextfor"webgl"and "experimental-webgl", WebGL2RenderingContextfor"webgl2"or ImageBitmapRenderingContextfor"bitmaprenderer". IfthecontextTypedoesn'tmatchapossibledrawingcontext,ordiffers fromthefirstcontextTyperequested,nullisreturned. ExamplesGiventhiselement: Youcangeta2dcontextofthecanvaswiththefollowingcode: varcanvas=document.getElementById('canvas'); varctx=canvas.getContext('2d'); console.log(ctx);//CanvasRenderingContext2D{/*...*/} Nowyouhavethe2Drendering contextforacanvasandyoucandrawwithinit.SpecificationsSpecificationHTMLStandard#dom-canvas-getcontext-devBrowsercompatibilityBCDtablesonlyloadinthebrowserSeealso CanvasRenderingContext2D.getContextAttributes() WebGLRenderingContext.getContextAttributes() Theinterfacedefiningit,HTMLCanvasElement. OffscreenCanvas.getContext() Availablerenderingcontexts:CanvasRenderingContext2D, WebGLRenderingContextandWebGL2RenderingContextand ImageBitmapRenderingContext. Foundaproblemwiththispage?EditonGitHubSourceonGitHubReportaproblemwiththiscontentonGitHubWanttofixtheproblemyourself?SeeourContributionguide.Lastmodified:Feb18,2022,byMDNcontributors



請為這篇文章評分?