[Knowledge of] the canvas getContext () method contextType parameters: '2d' / 'webgl' / 'webgl2' ...

Today occasionally come into contact with a laya project, which need to get to the canvas element on the page and operated.

1, then ran into the first problem: to get the canvas element is null

Outside the exclusion writing error, we take into account is that the page has not finished loading, so get less. This time can be a judge:

= window.onlaod function () { // when the jquery $ (document) using .ready (function () {}) may not be effective (when the case is dynamically generated canvas element) 
  // two differences: window. so after page onload when resources are loaded trigger $ (document) .ready be completed as long as the dom element drawn to trigger
var Canvas = document.getElementById ( 'layaCanvas' ); var context = canvas.getContext ( '2d' ); null // }

 

2, and then encountered a second problem, context acquisition is null

Baidu did not find many ways to get out why context is empty reasons, finally found understanding of what laya, laya project has canvas mode and webgl mode, when it is time to webgl mode by canvas.getContext ( '2d') nature It is to get less than modify the wording:

window.onload = function() {
    var canvas = document.getElementById("layaCanvas");
    var context = canvas.getContext('webgl2');
}

 

[Knowledge] summary

contextType following four parameters:

"2d": create a CanvasRenderingContext2D object as a 2D rendering context.
"Webgl" (or "experimental-webgl"): create a WebGLRenderingContext object as a 3D rendering context, only in the realization of the available experimental characteristics on WebGL browser 2.
"Webgl2": create a WebGL2RenderingContext object as a 3D rendering context, available only in the realization of the browser WebGL 3.
"Bitmaprenderer": Create a ImageBitmapRenderingContext, for rendering the bitmap to the canvas context, experimental characteristics.

 

[See article]

canvas in the getContext () method

Guess you like

Origin www.cnblogs.com/wannananana/p/12124114.html