为什么getContext()在Ubuntu的Chrome上返回null

时间:2019-05-03 16:00:54

标签: google-chrome ubuntu webgl

为什么在现有画布元素上调用getContext()会返回null, 但是在createElement('canvas')。getContext()时工作正常吗?

Ubuntu 18.04上的Chrome 72.0.3626.121

请参阅Chrome控制台: enter image description here

1 个答案:

答案 0 :(得分:1)

对Ubuntu而言并不特殊。您只能从特定画布获得一种类型的上下文。一旦获得了该画布的上下文,(a)您将无法为该画布获得任何其他类型的上下文;(b)如果您在该画布上请求了相同类型的上下文,您将获得与该画布相同的上下文。第一次,不是新的

const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');  // returns a Canvas2DRenderingContext
const gl = canvas.getContext('webgl');  // returns null because this canvas
                                        // already has a 2D context

反之亦然

const canvas = document.createElement('canvas');
const gl = canvas.getContext('webgl');  // returns a WebGLRenderingContext
const ctx = canvas.getContext('2d');    // returns null because this canvas
                                        // already has a WebGL context

关于它返回相同上下文的信息

const canvas = document.createElement('canvas');
const ctx1 = canvas.getContext('2d');  // returns a Canvas2DRenderingContext
const ctx2 = canvas.getContext('2d');  // returns the same Canvas2DRenderingContext

console.log(ctx1 === ctx2);  // true
ctx1.foo = "bar";
console.log(ctx2.foo);  // "bar" because it's the same object

每个上下文都属于一个特定的画布。不同的画布将获得不同的上下文

const canvas1 = document.createElement('canvas');
const canvas2 = document.createElement('canvas');
const ctx1 = canvas1.getContext('2d');  // returns a Canvas2DRenderingContext
const ctx2 = canvas2.getContext('2d');  // returns a different Canvas2DRenderingContext

console.log(ctx1 === ctx2);  // false