What's the difference between these two ways to get the canvas object
canvas = $('#canvasID');
canvas = document.getElementBy开发者_如何学GoId('canvasID');
What's the difference? why can't I use canvas.offset()
when i get the canvas object by the second way?
$('#canvasID')
uses jQuery to fetch the element.
document.getElementById('canvasID');
uses the browsers native implementation to fetch an element by it's ID.
The implementation of $("#canvasID")
differs among browsers, but i suspect that it actually uses document.getElementByID()
under the hood on all modern browsers.
The reason why you can't use offset
with the second method is because it's a method on the jQuery object (which is returned from $('#canvasID');
).
The .offset()
method is a jQuery method. The $()
function returns an array of jQuery wrapped objects matching the selector. So you can invoke jQuery methods on them. document.getElementById('canvasID');
returns the native DOM element which doesn't have such method defined.
with the first way, you're getting an jquery-object representing that element - and that jquery-object has an offset()
-method.
with getElementById()
you're getting a "plain" javascrip-object, with doesn't know this method.
$('#canvasID')
uses jQuery
document.getElementByID('canvasID')
uses the browsers native implementation, basically raw JavaScript.
You cannot use the .offset()
method because you're trying to use it on a non jQuery object.
offset()
is a jQuery method and can be applied to jQuery objects as returned by the $
(or jQuery
) function. To get a raw canvas object, access the elements of this object, with $('#canvasID')[0]
.
document.getElementById
returns the raw object. To get a jQuery object from a raw HTML object, call $
with it.
In summary:
var jquery_canvas = $('#canvas');
var raw_canvas = jquery_canvas[0];
var jquery_canvas_again = $(raw_canvas);
var context = raw_canvas.getContext('2d');
// NOT: jquery_canvas.getContext(), as getContext is only defined on raw object
var offset = raw_canvas.offset();
// NOT: raw_canvas.offset(), as offset is only defined on a jQuery object
精彩评论