1

I'm playing with a beginners tutorial about canvas

I was wondering if i can change this(which works straight from the tutorial):

     <script>  
        $(document).ready(function() {  
            var can = document.getElementById("myCanvas");  
            var ctx = canvas.getContext("2d");
            ctx.fillRect(50, 25, 150, 100);
        });  
    </script> 

into this:

 $(document).ready(function() { 
    can = $("mycanvas");
    var ctx = canvas.getContext("2d");
    ctx.fillRect(50, 25, 150, 100);
 }); 

or maybe even into

var ctx=$("mycanvas").getContext("2d");
ctx.fillRect(50,25,150,100);

something doesn't work and I can't figure out what? I tried adding .val() as i saw in countless articles

can=$("#mycanvas").val()

and also .atrr()

can=$("mycanvas").attr("id")

but to no avail what am i doing wrong? or maybe it isn't possible with jquery? I would be glad for any help with this.

alonisser
  • 11,542
  • 21
  • 85
  • 139

1 Answers1

4

It's .attr('id'), not .atrr('id').

To get the DOM node from a jQuery object, use the array subscript operator ([]) or the .get() method:

var can = $('#mycanvas')[0]; // or:
var can = $('#mycanvas').get(0);
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • and now it seems to work.. don't know what was wrong before - actually this also works: var ctx =$("#mycanvas")[0].getContext("2d"); and another link to the same problem I just found http://stackoverflow.com/questions/2925130/jquery-equivalent-of-getting-the-context-of-a-canvas/2925139#2925139 – alonisser Apr 22 '11 at 13:55