Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the canvas element by jquery?

Currently I'm play with the html5 canvas, the simple code is 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 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!

like image 860
Erxin Avatar asked Oct 11 '13 16:10

Erxin


People also ask

Does canvas use jQuery?

You can use JavaScript or JQuery to work with HTML Canvas.

What is jQuery canvas?

The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript. The <canvas> element is only a container for graphics. You must use JavaScript to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, text, and adding images.

Does HTML5 canvas use jQuery to draw on the screen?

HTML5 Canvas Sketchpad (Drawing) App will allow users to draw lines, scribble, write, sketch, etc. with mouse and touch screen. Inside the jQuery document ready event handler, the jQuery HTML5 Sketch plugin is applied to the HTML5 Canvas element.

What does the canvas element do?

<canvas> is an HTML element which can be used to draw graphics via scripting (usually JavaScript). This can, for instance, be used to draw graphs, combine photos, or create simple animations. First introduced in WebKit by Apple for the macOS Dashboard, <canvas> has since been implemented in browsers.


2 Answers

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")

like image 195
plomovtsev Avatar answered Sep 27 '22 21:09

plomovtsev


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

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

Otherwise, you're getting the jQuery object when you only do $("#cv"), so methods such as getContext will not work.

like image 42
Vivin Paliath Avatar answered Sep 27 '22 20:09

Vivin Paliath