简体   繁体   中英

How to access variable outside js function

Probably trivial, but I have no idea how to do it... I want to access img outside of createThumbnail. How can I do that?

Function

function createThumbnail(){
    canvas.deactivateAll().renderAll(); 
    html2canvas($('#chartdiv'), {
        onrendered: function(canvas) {
            var img = canvas.toDataURL("image/png"),
                elem = document.getElementById("thumbnail_img");
                elem.src = img;
        }
    });
}

You are setting a local variable to the onrendered callback. Move that outside of the function and then just assign that variable from within the function.

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;
    }
  });
}

See this article about closures

You can't by default, since img is declared inside the anonymous function. You'll have to assign it to something accessible from the outside.

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;
        }
    });
}

best is to return an object . so you can "use" createThumbnail multiple times (this isn't possible with a global variable ).

This way your code is nice and you don't make the function depending on your global scope / global variables.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM