Search code examples
javascripthtmlgoogle-chromecanvasblurry

How to make html5 canvas display crisp image based off chrome screencap


I am making a chrome extension that uses the chrome.tabs.captureVisibleTab method to grab a screencap of the current tab and then displays that in a popup from the chrome extension. If I use the img tag and use the data coming from the chrome function, such as data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwME…UUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAf/2Q==, the <img> displays pixel perfect, it is crisp and that's what I want. Problem is that I need to make it into a canvas, and when I do that, it becomes blurry.

This is a screencap of the <img> that uses the link data provided by Google to be used as a comparison to the canvas which is below.

This is the blurry canvas.

This is the code that I am using to try to do this, but I can't figure out how to make the canvas crisp like the image.

chrome.runtime.sendMessage({msg: "capture"}, function(response) {
    console.log(response.imgSrc);
    var img = document.createElement('img');
    var _canvas = document.createElement("canvas");
    img.src = response.imgSrc;
    img.height = 436;
    img.width = 800;
    document.getElementById('main-canvas').appendChild(img);
    draw(response);
});

function draw(response) {
    var canvas = document.getElementById('imageCanvas');
    canvas.height = window.innerHeight;
    canvas.width = window.innerWidth;
    //Get a 2d context
    var ctx = canvas.getContext('2d');
    //use image to paint canvas
    var _image = new Image();
    _image.onload = function() {
        ctx.drawImage(_image, 0, 0, 800, 436);
    }
    _image.src = response.imgSrc;

   document.getElementById('main-canvas').appendChild(canvas);
}

Solution

  • This is what I used to fix my problem: High Resolution Canvas from HTML5Rocks