Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selectors giving inconsistent behavior

Tags:

jquery

canvas

Can anyone explain the following behavior?

var ctx = $('#myCanvas').getContext("2d");      //doesnt work 
var ctx = $('#myCanvas')[0].getContext("2d");   //works
canvasWidth = $('#myCanvas').width();           //works
canvasHeight = $('#myCanvas').height();         //works
canvasWidth = $('#myCanvas')[0].width();        //doesnt work
canvasHeight = $('#myCanvas')[0].height();      //doesnt work
like image 701
Prakhar Avatar asked Dec 12 '22 13:12

Prakhar


1 Answers

$('#myCanvas') is a jQuery object. $('#myCanvas')[0] is a DOM element.

width() and height() are methods exposed by jQuery objects. You cannot call them on DOM elements, because they do not implement them (so far).

Likewise, getContext() is a method exposed by the <canvas> DOM element, and jQuery objects do not support it.

like image 71
Frédéric Hamidi Avatar answered Dec 30 '22 19:12

Frédéric Hamidi