Canvas has been tainted by cross-origin data via local chrome:// extension URL

2,272 views
Skip to first unread message

Stan Wiechers

unread,
Nov 10, 2013, 3:46:57 PM11/10/13
to Chromium-extensions

I am working on a google chrome extension and I am trying to load an image that is bundled with the extension into a canvas.

var canvas = document.createElement('canvas');
canvas.width = 470;
canvas.height = 470;
var context = canvas.getContext('2d');
var image = new Image();
image.addEventListener('load', function(){
     //process
});
image.src = get_url("asset/gotcha.png");

When I execute the code I am getting:

Unable to get image data from canvas because the canvas has been  tainted by
cross-origin data.

Is there a way to avoid this? I have successfully embedded images, audio, video and flash directly into target sites without any those issues.

Also posted to stackoverflow:
http://stackoverflow.com/questions/19894948

Thanks very much,
Stan

Stan Wiechers

unread,
Nov 11, 2013, 8:03:34 AM11/11/13
to Chromium-extensions
There is a solution btw:


Background Code:
chrome.extension.onRequest.addListener(
 function(request, sender, sendResponse) {
  if (request.message == "convert_image_url_to_data_url"){
        var canvas = document.createElement("canvas");
        var img = new Image();
        img.addEventListener("load", function() {
            canvas.getContext("2d").drawImage(img, 0, 0);
            sendResponse({data: canvas.toDataURL()}); 
        });
        img.src = request.url;
        }
    }
)

Content Code:
//@success is the callback
function local_url_to_data_url(url,success){    
  chrome.runtime.sendMessage({message: "convert_image_url_to_data_url",url:url}, 
           function(response) {success(response.data)}
    );  
}
--
"Local color. Soak it up"
Virginia Vidaura

http://www.merkwelt.com/people/stan/

Vlas Bashynskyi

unread,
Oct 24, 2016, 1:10:19 PM10/24/16
to Chromium-Extensions-Announce, st...@merkwelt.com
This is a very good solution, but you missed one thing. The default size of the canvas may not equal the size of the picture being painted on it, so you should add these lines before canvas.getContext(...):
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
Reply all
Reply to author
Forward
0 new messages