我需要提取原始图像大小的画布,但画布必须始终具有相同的宽度和高度,如果图像宽高比不同,则必须在画布中居中。我的意思是我将通过架构解释:
灰色 - 所有画布区域,在它上面(内部) - 图像
在这里你可以预览它:
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));
}
});
并且一切正常,除了一件事:当我执行canvas.toDataURL('image/jpeg', 100)
时,我只得到400 * 310px图像,但我需要原始尺寸(远大于400 * 310px)基于画布的数据图像,背景边框(在架构上为灰色等)。
这是真的吗?以及如何在不失去任何当前功能的情况下?
答案 0 :(得分:0)
您需要在画布最大宽度和高度
上更改画布宽度,高度和绘图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));
}
});