Javascript 从上下文获取画布
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5314674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get canvas from context
提问by pimvdb
Is there any way to obtain the canvas that a context is used for?
有没有办法获得上下文用于的画布?
Why I'm asking is because I'm creating a prototype function for CanvasRenderingContext2D
in which I need the width/height of the canvas element.
为什么我问是因为我正在创建一个原型函数CanvasRenderingContext2D
,我需要在其中使用画布元素的宽度/高度。
E.g.:
例如:
var cv = document.getElementById('canvas');
var ctx = cv.getContext('2d');
// Using only 'ctx', how to get 'cv'?
回答by Hyman Lawson
ctx.canvas
should return the canvas DOM node, from which you can get height and width.
ctx.canvas
应该返回画布 DOM 节点,您可以从中获取高度和宽度。
I tried it with https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_usage
我用https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Basic_usage试过了
Firefox was able to return ctx.canvas, as well as ctx.canvas.width and ctx.canvas.height. Also confirmed in Chrome.
Firefox 能够返回 ctx.canvas,以及 ctx.canvas.width 和 ctx.canvas.height。也在 Chrome 中得到确认。
回答by Drew Noakes
Try this to check for yourself:
试试这个来检查自己:
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var isSameObject = canvas === context.canvas;
alert(isSameObject
? 'context.canvas gives expected result'
: 'unexpected result');