I am trying to implement a very simple color picker chrome extension. The idea is simple.
- make use of the captureVisibleTab API provided by chrome to get screenshot of current page at regular intervals.
- load this screenshot in a canvas and then use get getImageData method for canvas context and display color values of the pixel based on the mouse coordinates.
I thought the idea was fairly simple to implement, but it actually did not turn out so well. Any help with the following snippets would be helpful:
background.js (working perfectly!)
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action == 'capture') {
chrome.tabs.captureVisibleTab(null, null, function(dataUrl) {
sendResponse({ imageUrl: dataUrl });
});
}
return true;
});
content_script.js
function fill_canvas(){
chrome.extension.sendMessage({action: 'capture'}, function(response) {
canvas = document.createElement('canvas');
canvas.width= $(window).width();
canvas.width= $(window).height();
canvasContext = canvas.getContext('2d');
var img = new Image();
img.onLoad = function(){
canvasContext.drawImage(img, 0, 0);
}
img.src = response.imageUrl;
});
}
$(document).ready(function(){
fill_canvas();
$(document).mousemove(function(e) {
pixelData = canvasContext.getImageData(e.offsetX,e.offsetY, 1, 1).data;
console.log(pixelData);
});
});
Please expect the surrounding code to be working correctly (like the simple activate extension button) and all relevant permissions granted in the manifest.
The output generated for pixelData looks Like:
[0, 0, 0, 0, byteLength: 4, byteOffset: 0, buffer: ArrayBuffer, subarray: function, set: function…]
which on opening contains lot's of info, except the one I need.
Cheers!