2010-08-26 33 views
4

在我的代碼的一部分中,我調用元素上的getContext('2d')來生成CanvasRenderingContext2D對象。這個對象繼續從函數到函數中傳遞,稍後在代碼中能夠得到對產生給定上下文的原始dom元素的引用會很方便。我無法在規範中找到任何規定,但它看起來應該是可能的。想法?從上下文獲取對Canvas元素的引用?

我可以想到很多解決方法(傳遞canvas元素及其上下文等),但我的代碼已經足夠複雜了,我寧願直接執行它。

回答

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; 
+2

好了,現在我很尷尬。我*發誓*我檢查了這樣的規範,我必須失明。謝謝! – 2010-08-26 20:46:51