【问题标题】:Get a reference to a Canvas element from its context?从上下文中获取对 Canvas 元素的引用?
【发布时间】:2011-04-04 10:36:57
【问题描述】:

在我的代码的一部分中,我在 canvas 元素上调用 getContext('2d') 以生成 CanvasRenderingContext2D 对象。该对象继续从一个函数传递到另一个函数,并且在代码的稍后位置,能够获得对产生给定上下文的原始canvas dom 元素的引用会很方便。我在规范中找不到任何提供此功能的东西,但这似乎应该是可能的。想法?

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

【问题讨论】:

    标签: html dom canvas


    【解决方案1】:

    所以你有你的上下文:

    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;
    

    【讨论】:

    • 好吧,现在我很尴尬。我发誓我检查了类似的规范,我一定是失明了。谢谢!
    猜你喜欢
    • 2014-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-19
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多