Search code examples
javascriptimagecanvascordovaresolution

Cordova iOS - CANVAS image resolution


I have an application where the users shoots or selects a picture and it gets displayed on a canvas (Cordova 3, iPhone4S) with Cordova Camera API.

Now I am experiencing a problem with image sizes. iPhone Screenshots, Landscape Photos, Portrait Photos all have different resolutions and sizes. And often the image gets cut or stretched in my canvas.

I tried it with image tag before. That worked well. But I am having problem with canvas.

At the moment I have

var canvas = document.getElementById("myCanvas");
canvas.width = 640;
canvas.height = 960;
canvas.style.width = "100%";
canvas.style.height = "100%";

It works if I load a screenshot in the canvas, but if I load a photo in the canvas it gets cut.

Here two photo examples (portrait and landscape) loaded from iPhone's photo library.

How it is:

enter image description here

How it should be:

(the one at the bottom)

enter image description here

How it is:

enter image description here

How it should be:

enter image description here

Any Idea how to get the canvas to display the full image with every ing size/resolution?

Thank you.


Solution

  • I figured it out myself. I just added targetWidth and targetHeight to the camera.getPicture function

    var canvas = document.getElementById("myCanvas");
    canvas.width = 600;
    canvas.height = 960;
    canvas.style.width = "300px";
    canvas.style.height = "480px";
    

    camera function

    navigator.camera.getPicture(funcSuccess, funcError, { quality: 100, targetWidth: 600, targetHeight: 960, destinationType: destinationType.FILE_URI, sourceType: source });
    

    In the success function:

    canvas.drawImage(img, 0, 0);
    

    anyway... because I am using different caves.width/height and canvas.style.with/height (for retina optimized) I now have another problem. My function to get the clicked pixels colors does not work properly.

    I am using this (first answer): Get pixel color from canvas, on mouseover in my canvas tap event. But when using retina sizes it always returns false colors. Like it reads the pixels expecting that the image is 600x960 instead of 300x480 in an 600x960 pixel canvas.

    Anyone any Idea?