javascript - 使用 Canvas 裁剪图像 - 结果是小图像

标签 javascript canvas

我正在尝试使用 Canvas 裁剪图像。
原始图像为 2217 x 790。
加载到页面时,它缩放至 1515 x 540
Canvas 尺寸为 960 x 540。
图像和 Canvas 都位于屏幕中央,因此水平对齐。
我需要裁剪中心区域 - 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!

最佳答案

请参阅我的评论,了解宽度属性和宽度样式之间的差异。它们并不完全相同。此外,我只是做了一个 fiddle ,因为你没有,而且我没有得到同样的行为!下载的图片尺寸为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);

关于javascript - 使用 Canvas 裁剪图像 - 结果是小图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49965206/

相关文章:

javascript:使用转义双引号创建 SQlite 语句

javascript - jQuery 显示 div 加载 onclick

javascript - Rails 4 turbolinks 导致 html Canvas 在 ipad 上消失

javascript - Flot:如何在条形图中设置数字样式?

javascript - Fabric.js 中的多个 Canvas (页面)

javascript - anchor 标记下载属性不起作用 :Bug in Chrome 35. 0.1916.114

javascript - Backbones 使用原型(prototype)来定义类

javascript - Safari createPattern 失败并显示 SVG : suggestions for alternatives?

html - KineticJS 是否有对 SVG 的库支持?

javascript - 调试 JavaScript 计时事件