从上下文中获取对Canvas元素的引用? [英] Get a reference to a Canvas element from its context?

查看:253
本文介绍了从上下文中获取对Canvas元素的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在代码的一部分中,我在 canvas 元素上调用 getContext('2d') CanvasRenderingContext2D对象。该对象继续在各个函数之间传递,并且在代码的稍后一点,能够获得对原始 canvas 产生给定上下文的dom元素。我在规范中找不到提供此功能的任何东西,但似乎应该可以做到。有想法吗?



我可以想到很多解决方法(将canvas元素及其上下文等传递给我),但是我的代码已经足够复杂了,我宁愿直接这样做。

解决方案

因此,您拥有自己的环境:

  var ctx = myCanvas.getContext('2d'); //画布的2d上下文

以后您总是可以这样做:

  ctx.canvas //上下文的画布,在这种情况下与myCanvas 


来自画布规格

  interface CanvasRenderingContext2D {

//向后引用画布
的readonly属性HTMLCanvasElement canvas;


In one part of my code, I call getContext('2d') on a canvas element to produce a CanvasRenderingContext2D object. That object goes on to get passed around a fair bit from function to function, and at a later point in the code it'd be handy to be able to get a reference to the original canvas dom element that produced a given context. I can't find anything in the spec that provides for this, but it seems like the sort of thing that ought to be possible. Ideas?

I can think of plenty of workarounds (pass the canvas element along with its context, etc.) but my code's complicated enough already and I'd rather do it directly.

解决方案

So you've got your context:

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

later on you can always do:

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

From the Canvas spec:

interface CanvasRenderingContext2D {

  // back-reference to the canvas
  readonly attribute HTMLCanvasElement canvas;

这篇关于从上下文中获取对Canvas元素的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆