从上下文中获取对Canvas元素的引用?

时间:2010-08-26 18:24:50

标签: html5 dom canvas

在我的代码的一部分中,我在getContext('2d')元素上调用canvas来生成CanvasRenderingContext2D对象。该对象继续在函数之间传递一个相当大的位,并且在代码的稍后部分,能够获得对生成给定的原始canvas dom元素的引用是很方便的。上下文。我在规范中找不到任何东西,但似乎应该是可能的那种东西。想法?

我可以想到很多变通方法(传递canvas元素及其上下文等),但我的代码已经足够复杂了,我宁愿直接进行。

1 个答案:

答案 0 :(得分:10)

所以你有你的背景:

var ctx = myCanvas.getContext('2d'); // the canvas' 2d context

稍后您可以随时执行:

ctx.canvas // the context's canvas, which in this case is the same as myCanvas

来自Canvas spec

interface CanvasRenderingContext2D {

  // back-reference to the canvas
  readonly attribute HTMLCanvasElement canvas;
相关问题