jQuery 如何通过jquery获取canvas元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19323235/
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
How to get the canvas element by jquery?
提问by Erxin
Currently I'm play with the html5 canvas, the simple code is below:
目前我正在使用 html5 画布,简单的代码如下:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script src="Scripts/jquery-2.0.3.min.js"></script>
<script>
$(function () {
//THIS WILL NOT WORK!
//var cv = $("#cv");
//THIS WORKS FINE.
var cv = document.getElementById("cv");
ct = cv.getContext("2d");
var mText = "hi";
var x = cv.width / 2;
var y = cv.height / 2;
ct.textAligh = "center";
ct.fillText(mText, x, y);
});
</script>
</head>
<body>
<div style="width:200px; height:200px; margin:0 auto; padding:5px;">
<canvas id="cv" width="200" height="200" style="border:2px solid black">
Your browser doesn't support html5! Please download a fitable browser.
</canvas>
</div>
</body>
</html>
The canvas element could only be picked by the method document.getElementById, but the jQuery method is not working. Is there a way to get the original html from the jquery object or am I miss using something? Thanks in advance!
画布元素只能由方法 document.getElementById 选取,但 jQuery 方法不起作用。有没有办法从 jquery 对象中获取原始 html 还是我错过了使用某些东西?提前致谢!
回答by mopdobopot
jQuery's $(<selector>)
returns a collection of nodes (in fact it is "object masquerades as an array" as the doc says) so just use $('#cv').get(0)
instead of document.getElementById("cv")
jQuery$(<selector>)
返回一个节点集合(实际上它是“对象伪装成一个数组”,正如文档所说)所以只需使用$('#cv').get(0)
而不是document.getElementById("cv")
回答by Vivin Paliath
回答by Einacio
using get()
使用 get()
explore the jquery doc, it's very useful
探索 jquery 文档,它非常有用