How to get canvas element by jquery?

I am currently playing with html5 canvas, a simple code below:

<!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 can only be selected by the document.getElementById method, but the jQuery method does not work. Is there a way to get the original html from a jquery object, or am I missing something? Thanks in advance!

+6
source share
3 answers

jQuery $(<selector>) returns a collection of nodes (actually it's a “masquerade object as an array” as doc says ), so just use $('#cv').get(0) instead of document.getElementById("cv")

+13
source

You need to use .get() to get the actual DOM element:

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

Otherwise, you get a jQuery object when you execute only $("#cv") , so methods like getContext will not work.

+5
source

using get ()

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

examine jquery doc it is very useful

+4
source

Source: https://habr.com/ru/post/955791/


All Articles