You can't directly pass an image from your extension to a web-page's canvas without making it tainted.
This is a work-around:
Description:
- You access the image from your background page (or content script).
- You put it in a canvas and convert it to a dataURL.
- You inject some JS code into the web-page, passing the dataURL as a string.
- The injected code uses the string (dataURL) to create an image (in the context of the web-page) and draw it onto a canvas.
Sample code:
/* In `background.js` */
function injectImg(tabID, remoteCanvasID, imgPath) {
var canvas = document.createElement("canvas");
var img = new Image();
img.addEventListener("load", function() {
canvas.getContext("2d").drawImage(img, 0, 0);
var dataURL = canvas.toDataURL();
var code = [
"(function() {",
" var canvas = document.getElementById(\"" + remoteCanvasID + "\");",
" var img = new Image();",
" img.addEventListener(\"load\", function() {",
" canvas.getContext(\"2d\").drawImage(img, 0, 0);",
" });",
" img.src = \"" + dataURL + "\";",
" ",
"})();"].join("\n");
chrome.tabs.executeScript(tabID, { code: code });
});
img.src = chrome.extension.getURL(imgPath);
}
chrome.runtime.onMessage.addListener(function(msg, sender)) {
if (msg.action && (msg.action == "getImg")
&& msg.imgPath && msg.canvasID) {
injectImg(sender.tab.id, msg.canvasID, msg.imgPath);
}
});
/* In `content.js` */
chrome.runtime.sendMessage({
action: "getImg",
imgPath: "some/image.png",
canvasID: "someCanvasID"
});
This is a more generic approach (that can be used by any content script with minimum configuration), but it might be simpler to move part of the logic to the content script. E.g.:
- Define a function within the content script, that when called with a dataURL creates and draws an image onto a canvas.
- Define a function in the background page, that takes an image-path and returns a dataURL (as seen above).
- Use chrome.runtime.getBackgroundPage() to get a reference to the background page's
window
object, call the function to convert an image-path to a dataURL and finally use that dataURL to create an image and draw it onto a canvas.