JS画布在各方面调整大小

时间:2017-03-20 11:12:36

标签: javascript html5 canvas

我正在尝试向所有方向调整画布大小the way Photoshop does

我尝试使用JS,但它与Photoshop CC画布尺寸功能的输出不匹配。

原始图像(600 x 439):http://i.imgur.com/rXURSWC.jpg

使用JS代码(580 x 430)调整大小:http://i.imgur.com/fwUiHyF.png

使用Photoshop CC调整大小(图像 - >画布大小)(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>

所以,任何想法如何我可以像photoshop CC那样在所有方向上调整画布大小,以便它可以匹配Photoshop CC的输出。

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

2 个答案:

答案 0 :(得分:1)

您要求的只是裁剪图像,但将锚点保持在中间位置。

这很容易实现:
x的{​​{1}}和y参数设置为所需大小与原始大小之差除以2。

&#13;
&#13;
drawImage
&#13;
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';
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以通过在图片加载时重新定义画布widthheight来完成此操作...

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>