我是棱角分明的新人。我无法想象如何访问函数()中的变量。这是我的代码
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 - 问题是角度无法在 printvalue()上找到 var a 它仅在函数内部工作()
答案 0 :(得分:0)
像这样转换你的代码
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';
}
答案 1 :(得分:0)
在这里你要创建一个范围变量并访问整个组件,
在angularJS之前,有一个$ scope变量,你可以在其中访问整个变量,在最新的角度版本中,你需要使用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';
}