使用画布裁剪图像 - 结果是小图像

时间:2018-04-22 11:03:18

标签: javascript canvas

我尝试使用画布裁剪图像 原始图像是2217 x 790.
在页面上加载它被缩放到1515 x 540
帆布是960 x 540.
图像和画布都位于屏幕中央,因此水平对齐 我需要裁剪中心区域 - 960 x 540.

var img = document.getElementById("imgt");
var canvas = document.getElementById("canvasa");
var ctx = canvas.getContext("2d");

var a = $('#imgt').width() - 960;
var a = a/2; // this is 277.7...

ctx.drawImage(img, a, 0, 960, 540, 0, 0, 960, 540);
//also tried:
ctx.drawImage(img, 0, 0, 960, 540, 0, 0, 960, 540);

var newimg = new Image();
newimg.src = canvas.toDataURL('image/jpeg');

var dl = document.createElement("a");
dl.href = canvas.toDataURL("image/jpeg");
dl.download = true;
document.body.appendChild(dl);
dl.click();

下载newimg我看到的内容 - 300 x 150

2 个答案:

答案 0 :(得分:1)

请参阅我的评论,将宽度属性和宽度之间的差异视为样式。它们并不完全相同。此外,我只是做了一个小提琴,因为你没有,我没有得到相同的行为!下载的图像是960 * 540

HERE - fires with delay

ONLOAD

setTimeout(function(){
  var canvas = document.createElement("canvas");
  canvas.width = "960";
  canvas.height="540";
  var ctx = canvas.getContext("2d");
  ctx.drawImage(document.images[0], 0, 0, 960, 540, 0, 0, 960, 540);
  var a = document.createElement("a");
  a.download = "image.jpeg";
  a.href = canvas.toDataURL("image/jpeg");
  a.click();
},5000);

答案 1 :(得分:1)

通常,如果要从源图像裁剪区域,并将其绘制到画布而不破坏宽高比而不将维度硬编码到例程中,则可以执行以下操作:

const canvasAspectRatio = canvas.width / canvas.height;

const cropWidth = canvas.width;
const cropHeight = cropWidth / canvasAspectRatio;
const sx = img.width / 2 - cropWidth / 2;
const sy = img.height / 2 - cropHeight / 2;

ctx.drawImage(img, sx, sy, cropWidth, cropHeight, 0, 0, canvas.width, canvas.height);

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const img = document.getElementById('img');

const canvasAspectRatio = canvas.width / canvas.height;
// Crop central canvas sized rectangle area into canvas
const cropWidth = canvas.width;
const cropHeight = cropWidth / canvasAspectRatio; // Here you should calculate the height based on aspect ratio instead of assuming it matches that of the canvas
const sx = img.width / 2 - cropWidth / 2;
const sy = img.height / 2 - cropHeight / 2;

ctx.drawImage(img, sx, sy, cropWidth, cropHeight, 0, 0, canvas.width, canvas.height);
body {
  background-color: black;
}

#img {
  visibility: hidden;
}

#canvas {
  border: 1px solid #f00;
}
<canvas id="canvas" width="960" height="540"></canvas>
<img id="img" src="http://via.placeholder.com/2217x790">

相关问题