GtwoK
GtwoK

Reputation: 581

"Uncaught TypeError: Cannot read property 'getContext' of undefined" when drawing on canvas

I'm getting the above error whenever I call my function that should simply draw a circle on a canvas. The error occurs on the line var ctx = c.getContext("2d"); My document is laid out as such:

The function that should draw the circle is in the head:

function circleTrans() {
  var c = $(this).find('canvas')[0];
  var ctx = c.getContext("2d");
  ctx.beginPath();
  ctx.arc(95,50,40,0,2*Math.PI);
  ctx.stroke();
}

The event that calls the function is also in the head, after the above.:

$(".projectContainer").click(function(){
  circleTrans();
});

So when clicking on one of the multiple "projectContainer" divs the canvas in that respective div should draw a circle. Here is where the projectContainer is, later in the body:

    <div class="projectContainer" name="Film Festival">
        <canvas class="canvases"></canvas>
    </div>

Anyone know the cause of the error?

Upvotes: 0

Views: 4002

Answers (2)

Suman Bogati
Suman Bogati

Reputation: 6349

As Adeneo said, this is not element, there is another way through which you can pass the element like,

$(".projectContainer").click(function(){
  circleTrans(this);
  //pass element-^
});

Get div element as parameter cthis

function circleTrans(cthis) {
              //--------^
  var c = $(cthis).find('canvas')[0];
  var ctx = c.getContext("2d");
  ctx.beginPath();
  ctx.arc(95,50,40,0,2*Math.PI);
  ctx.stroke();
}

Upvotes: 0

adeneo
adeneo

Reputation: 318212

The way you're calling the function, this is not the element.

Reference it like this to get the right value of this

$(".projectContainer").on('click', circleTrans);

Upvotes: 1

Related Questions