Search code examples
javascriptcanvasgoogle-chrome-extensionhtml5-canvas

Not being able to Load Image from a function To HTML Canvas


I am trying to place the screenshot image into html canvas but not being able to. I have taken screenshot of current tab by using following chrome API. Trying to make a chrome extension.

/* background.js */
let id = 100;
//calling chrome api
chrome.browserAction.onClicked.addListener(() => {
    chrome.tabs.captureVisibleTab((screenshotUrl) => {
        const viewTabUrl = chrome.extension.getURL('screenshot.html?id=' + id++)
        let targetId = null;
        //checking if the opened tab id is the same as the target id
        chrome.tabs.onUpdated.addListener(function listener(tabId, changedProps) {
            if (tabId != targetId || changedProps.status != "complete")
                return;
            chrome.tabs.onUpdated.removeListener(listener);
            const views = chrome.extension.getViews();
            for (let i = 0; i < views.length; i++) {
                let view = views[i];
                if (view.location.href == viewTabUrl) {
                    view.setScreenshotUrl(screenshotUrl);
                    return;
                }
            }
        });

        //chrome tabs create method
        //no listener on create event because the tab’s URL may not be set at the time this event is fired
        chrome.tabs.create({ url: viewTabUrl }, (tab) => {
            targetId = tab.id;
        });
    });
});

But not able to call the image from the function

function setScreenshotUrl(url) {
    document.getElementById('target').src = url;
};


var cnv = document.getElementById("conv");

cnv.onclick = function() {
    var x = document.getElementById("target").src;
    document.getElementById("demo").innerHTML = x;
};


window.addEventListener('load', function() {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = document.getElementById("target");

    ctx.drawImage(img, 10, 10, 300, 175, 0, 0, 100, 175);
});

Solution

  • The problem was image was not ready at windows on load event, verified by checking the innerHTML of the image, while if I try to do the same thing in onClick event, the image is successfully loaded into canvas.