gpt4 book ai didi

函数内的 Angular 访问变量

转载 作者:行者123 更新时间:2023-12-02 16:07:23 24 4
gpt4 key购买 nike

我是 Angular 新手。我不知道如何访问 function() 内的变量。这是我的代码

  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';


}

现在我需要从另一种方法访问“imgurl”

 printvalue(){
need to access imgurl
}

编辑1 - 问题是 Angular 无法在printvalue()上找到var a,它仅在函数something()内工作

最佳答案

在这里,您想要创建一个作用域变量并在整个组件中进行访问,早期的 AngularJS 中,有 $scope 变量,您可以在其中访问整个变量,在最新的 Angular 版本中,您需要使用 this 来访问整个变量。

所以你需要尝试

     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';


}

关于函数内的 Angular 访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49313867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com