skip to Main Content

I am trying to resize a canvas in all directions the way Photoshop does.

I tried with JS but it’s not matching the output I got from the Photoshop CC canvas size feature.

Original Image (600 x 439): http://i.imgur.com/rXURSWC.jpg

Resized with JS code (580 x 430): http://i.imgur.com/fwUiHyF.png

Resized with Photoshop CC (Image->Canvas Size) (580 x 430): http://i.imgur.com/smXTNv2.jpg

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x = 0;
var y = 0;
var width = 580;
var height = 430;

var imageObj = new Image();
imageObj.onload = function() {
    context.drawImage(imageObj, x, y, width, height);
};
imageObj.src = 'https://i.imgur.com/rXURSWC.jpg';
<body>
    <canvas id="myCanvas" width="580" height="430"></canvas>
</body>

So, any idea how I can resize canvas in all directions the way photoshop CC does so that it can match to output of Photoshop CC.

JSFiddle: https://jsfiddle.net/f2L4b942/

2

Answers


  1. You could accomplish this by redefining the canvas width and height upon image load …

    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
    var x = 0;
    var y = 0;
    var imageObj = new Image();
    imageObj.onload = function() {
        canvas.width = this.width;
        canvas.height = this.height;
        context.drawImage(imageObj, x, y);
    };
    imageObj.src = 'http://i.imgur.com/rXURSWC.jpg';
    body {
      margin: 0px;
      padding: 0px;
    }
    #myCanvas {
      border: 1px solid black;
    }
    <canvas id="myCanvas" width="580" height="430"></canvas>
    Login or Signup to reply.
  2. What you are asking for is just to crop your image, but keep the anchor point in the middle.

    This is easily implemented :
    Set the x and y parameters of drawImage to the difference between the required size and the original one, divided by 2.

    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
    var requiredWidth = canvas.width = 580;
    var requiredHeight = canvas.height = 430;
    var img = new Image();
    
    img.onload = function() {
      // all you need is here
      var offsetX = (requiredWidth - img.naturalWidth) / 2;
      var offsetY = (requiredHeight - img.naturalHeight) / 2;
      
      context.drawImage(img, offsetX, offsetY, img.naturalWidth, img.naturalHeight);
    };
    img.src = 'http://i.imgur.com/rXURSWC.jpg';
    <canvas id="myCanvas" width="580" height="430"></canvas>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search