Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

canvas.getContext is not a function

I have written a simple template for a AngularJs directive:

<div class="circle">
    <canvas></canvas>
</div>

My directive has the following look:

MobileApp.directive('circle', function () {
    return {
        restrict: 'E',
        scope: true,
        link: function (scope, elem, attrs) {
            ...
            var canvas = elem.find('canvas');
            var ctx = canvas.getContext('2d');
            ...
        }
    }
});

And the usage of that is simple enough:

<circle/>

I am getting an error when trying to call a method getContext('2d'):

TypeError: canvas.getContext is not a function

The canvas instance is selected and its JSON representation looks

{
  "0": {},
  "length": 1,
  "prevObject": {
    "0": {},
    "context": {},
    "length": 1
  },
  "context": {},
  "selector": "canvas"
}

I have already read about all related questions here, but the answer hasn't been found. Any help would be appreciated. Thanks.

like image 304
Andrew Tobilko Avatar asked Sep 19 '26 08:09

Andrew Tobilko


2 Answers

I create a little plunker. In your sample i don't understand the relation between directive and template. Have you missing to add template property ? What i do in plunker :

Define template :

return {
    restrict: 'E',
    scope: true,
    template: '<div><canvas></canvas></div>',
    link: function (scope, elem, attrs) {
        var canvas = elem.find('canvas');
        console.log(canvas);
        var ctx = canvas[0].getContext('2d');
        console.log(canvas, ctx);
    }
}

Get canvas from the object that return by find method :

var ctx = canvas[0].getContext('2d');

And the use :

<circle></circle>
like image 143
Silvinus Avatar answered Sep 21 '26 22:09

Silvinus


Replace var canvas = elem.find('canvas'); by var canvas = elem.find('canvas')[0];

like image 39
Piyush.kapoor Avatar answered Sep 21 '26 21:09

Piyush.kapoor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!