How to get pixel data from canvas which contains t

2019-06-10 03:58发布

问题:

I am trying to implement a very simple color picker chrome extension. The idea is simple.

  1. make use of the captureVisibleTab API provided by chrome to get screenshot of current page at regular intervals.
  2. 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!

回答1:

As javascript is case-sensitive your onLoad will never kick in (no camel-case for events). Try to lower-case it:

// onload not onLoad
img.onload = function(){
    canvasContext.drawImage(img, 0, 0);
}

I also noticed you put the canvas and context on the global scope (window). I would guess (I am not familiar with Chrome's extension api) that the api prevents or isolates the window object (seals or freezes it).

Modify these and I am pretty sure, wo/ testing, it would work:

//use 'var' in front
var canvas = document.createElement('canvas');
var canvasContext = canvas.getContext('2d');

or define them outside this function (you don't show if you do this already).