可能微不足道,但我不知道怎么做...我想在createThumbnail之外访问img。我怎么能这样做?
function createThumbnail(){
canvas.deactivateAll().renderAll();
html2canvas($('#chartdiv'), {
onrendered: function(canvas) {
var img = canvas.toDataURL("image/png"),
elem = document.getElementById("thumbnail_img");
elem.src = img;
}
});
}
答案 0 :(得分:3)
您正在为onrendered
回调设置一个局部变量。将其移到函数外部,然后从函数中分配该变量。
var img; //Set empty variable here.
function createThumbnail(){
canvas.deactivateAll().renderAll();
html2canvas($('#chartdiv'), {
onrendered: function(canvas) {
var elem;
img = canvas.toDataURL("image/png");
elem = document.getElementById("thumbnail_img");
elem.src = img;
}
});
}
答案 1 :(得分:1)
默认情况下,您不能在匿名函数内声明img
。您必须将其分配给可从外部访问的内容。
var accessibleImg;
function createThumbnail(){
canvas.deactivateAll().renderAll();
html2canvas($('#chartdiv'), {
onrendered: function(canvas) {
var img = canvas.toDataURL("image/png"),
elem = document.getElementById("thumbnail_img");
elem.src = img;
accessibleImg = img;
}
});
}
答案 2 :(得分:1)
最好是返回一个对象。所以你可以"使用" createThumbnail多次(不可能使用全局变量)。
这样你的代码很好,你不能根据你的全局范围/全局变量来创建函数。
function createThumbnail(){
canvas.deactivateAll().renderAll();
var img = {}, elem;
html2canvas($('#chartdiv'), {
onrendered: function(canvas) {
img.dataUrl = canvas.toDataURL("image/png"),
elem = document.getElementById("thumbnail_img");
elem.src = img;
}
});
return img;
}
var img = createThumbnail();
var dataUrl = img.dataUrl; // contains the dataUrl from the canvas when onrendered was called