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

1zmg4dgp  于 2023-10-14  发布在  Go
关注(0)|答案(1)|浏览(111)

为什么getContext()在现有的canvas Element上调用时返回null,但在调用canvas Element('canvas').getContext()时工作正常?
Ubuntu 18.04上的Chrome 72.0.3626.121
参见Chrome控制台:

bvhaajcl

bvhaajcl1#

这对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

关于it返回相同的上下文

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

相关问题