Stephen Reynolds
Stephen Reynolds

Reputation: 55

angular access variable inside a function

I'm new to angular. I couldn't figure how to access a variable inside a function(). this is my code

  mergeImages() {
    var imgurl;
    var canvas: HTMLCanvasElement = this.canvas.nativeElement;
    var context = canvas.getContext('2d');


    let img1 = new Image();
    let img2 = new Image();

    img1.onload = function() {
      canvas.width = img1.width;
      canvas.height = img1.height;
      context.globalAlpha = 1.0;
      img2.src = '../assets/sun.jpg';
    };
    img2.onload = function() {
      context.globalAlpha = 1;
      context.drawImage(img1, 0, 0);
      context.globalAlpha = 0.5; //Remove if pngs have alpha
      context.drawImage(img2, 0, 0);

       imgurl = canvas.toDataURL("image/jpg");
      //console.log(imgurl)

    };
    img1.src = '../assets/moon.jpg';


     }

now I need to access "imgurl" from another method

 printvalue(){
   need to access imgurl
}

edit 1 - problem is angular cannot find var a on printvalue() it's only working inside function something()

Upvotes: 4

Views: 15272

Answers (2)

Hrishikesh Kale
Hrishikesh Kale

Reputation: 6548

here you want to make a scope variable and access throughout the component, earlier in angularJS, there was $scope variable where you could access that variable throughout, in the latest angular version you need to use this to access throughout.

so you need to try

     imgurl : string;
mergeImages() {

    var canvas: HTMLCanvasElement = this.canvas.nativeElement;
    var context = canvas.getContext('2d');


    let img1 = new Image();
    let img2 = new Image();

    img1.onload = () => {
      canvas.width = img1.width;
      canvas.height = img1.height;
      context.globalAlpha = 1.0;
      img2.src = '../assets/sun.jpg';
    };
    img2.onload = () => {
      context.globalAlpha = 1;
      context.drawImage(img1, 0, 0);
      context.globalAlpha = 0.5; //Remove if pngs have alpha
      context.drawImage(img2, 0, 0);

       this.imgurl = canvas.toDataURL("image/jpg");
      //console.log(imgurl)

    };
    this.img1.src = '../assets/moon.jpg';


     }

Upvotes: 3

Anas
Anas

Reputation: 991

Convert your code like this

let imgurl;
mergeImages() {

    var canvas: HTMLCanvasElement = this.canvas.nativeElement;
    var context = canvas.getContext('2d');


    let img1 = new Image();
    let img2 = new Image();

    img1.onload = () => {
      canvas.width = img1.width;
      canvas.height = img1.height;
      context.globalAlpha = 1.0;
      img2.src = '../assets/sun.jpg';
    };
    img2.onload = () => {
      context.globalAlpha = 1;
      context.drawImage(img1, 0, 0);
      context.globalAlpha = 0.5; //Remove if pngs have alpha
      context.drawImage(img2, 0, 0);

       this.imgurl = canvas.toDataURL("image/jpg");
      //console.log(imgurl)

    };
    this.img1.src = '../assets/moon.jpg';


     }

Upvotes: 1

Related Questions