html5 canvas with image: save original imagesize

983 views Asked by At

I need to extract original image-size canvas, but canvas must be always the same width and height, and if image aspect ration is different, it must be centered in canvas. What i mean i will explain by schema:

enter image description here

enter image description here

gray - all canvas area, over it (inner) - image

here you could preview it:

http://plnkr.co/edit/IBE35kJqNM3tSI8J3BqL?p=preview

$(function() {
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");
  var cw = canvas.width;
  var ch = canvas.height;

  var img = new Image();
  img.onload = start;
  img.setAttribute('crossOrigin', 'anonymous');
  img.src = "https://dl.dropboxusercontent.com/u/59666091/Audi-RS7-Sportback-1.jpg";

  function start() {

    var MAX_WIDTH = 400;
    var MAX_HEIGHT = 310;
    var iw = img.width;
    var ih = img.height;

    var scale = Math.min((MAX_WIDTH / iw), (MAX_HEIGHT / ih));
    var sw = iw * scale;
    var sh = ih * scale;

    ctx.drawImage(img,
      0, 0, iw, ih, (canvas.width - sw) / 2, (canvas.height - sh) / 2, iw * scale, ih * scale
    );

    console.log(canvas.toDataURL('image/jpeg', 100));
  }

});

and all is ok, except one thing: when i execute canvas.toDataURL('image/jpeg', 100) i get only 400*310px image, but i need originial-size (much bigger then 400*310px) canvas-based data image, with background borders (as gray on schema etc).

is it real to do? and how, without loosing any current functionality?

1

There are 1 answers

2
Paulius Sapragonas On

You need change canvas width,height and drawing on the canvas max width and height

http://plnkr.co/edit/hycPgkjbT5YCzZPN3Rrm?p=preview

$(function() {
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");
  var cw = canvas.width;
  var ch = canvas.height;

  var img = new Image();
  img.onload = start;
  img.setAttribute('crossOrigin', 'anonymous');
  img.src = "https://dl.dropboxusercontent.com/u/59666091/Audi-RS7-Sportback-1.jpg";


      function start() {

        var MAX_WIDTH = img.width;
        var MAX_HEIGHT = img.height;
        var iw = img.width;
        var ih = img.height;

        $('#canvas').attr('width', img.width);
        $('#canvas').attr('height', img.height);

        var scale = Math.min((MAX_WIDTH / iw), (MAX_HEIGHT / ih));
        var sw = iw * scale;
        var sh = ih * scale;

        ctx.drawImage(img,
          0, 0, iw, ih, (canvas.width - sw) / 2, (canvas.height - sh) / 2, iw * scale, ih * scale
        );

        console.log(canvas.toDataURL('image/jpeg', 100));
      }

    });