【问题标题】:How to get the canvas element by jquery?jquery如何获取canvas元素?
【发布时间】:2013-10-11 16:42:57
【问题描述】:

目前我正在玩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>

canvas 元素只能通过 document.getElementById 方法获取,但是 jQuery 方法不起作用。有没有办法从 jquery 对象中获取原始 html 或者我错过了使用某些东西? 提前致谢!

【问题讨论】:

  • 您必须使用索引[0] 将jQuery 对象转换为DOM 元素var cv = $('#cv')[0]
  • @devnull69 是的,它有效,谢谢!

标签: javascript jquery html canvas


【解决方案1】:

jQuery 的$(&lt;selector&gt;) 返回一个节点集合(实际上它是“对象伪装成数组”as the doc says)所以只需使用$('#cv').get(0) 而不是document.getElementById("cv")

【讨论】:

    【解决方案2】:

    您需要使用.get() 来获取实际的 DOM 元素:

    var canvas = $("#cv").get(0);
    

    否则,当您只执行$("#cv") 时,您将获得jQuery 对象,因此getContext 等方法将不起作用。

    【讨论】:

      【解决方案3】:

      使用 get()

      http://api.jquery.com/get/

      浏览 jquery 文档,它非常有用

      【讨论】:

      • 我只检查了jquery的属性,忘记了jquery返回一组已建立的元素。
      猜你喜欢
      • 1970-01-01
      • 2014-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-20
      • 1970-01-01
      • 2012-03-21
      • 2021-08-01
      相关资源
      最近更新 更多