[英]html5 canvas with image: save original imagesize
I need to extract original image-size canvas, but canvas must be always the same width and height, and if image aspect ration is different, it must be centered in canvas.我需要提取原始图像大小的画布,但画布的宽度和高度必须始终相同,如果图像纵横比不同,则必须在画布中居中。 What i mean i will explain by schema:
我的意思是我将通过模式解释:
gray - all canvas area, over it (inner) - image灰色 - 所有画布区域,在它上面(内部) - 图像
here you could preview it:在这里你可以预览它:
http://plnkr.co/edit/IBE35kJqNM3tSI8J3BqL?p=preview 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));
}
});
and all is ok, except one thing: when i execute canvas.toDataURL('image/jpeg', 100)
i get only 400*310px image, but i need originial-size (much bigger then 400*310px) canvas-based data image, with background borders (as gray on schema etc). canvas.toDataURL('image/jpeg', 100)
,除了一件事:当我执行canvas.toDataURL('image/jpeg', 100)
我只得到 400*310px 的图像,但我需要原始大小(比 400*310px 大得多)基于画布的数据图像,带有背景边框(如模式上的灰色等)。
is it real to do?这是真的吗? and how, without loosing any current functionality?
以及如何在不丢失任何当前功能的情况下?
You need change canvas width,height and drawing on the canvas max width and height您需要更改画布宽度、高度并在画布上绘制最大宽度和高度
http://plnkr.co/edit/hycPgkjbT5YCzZPN3Rrm?p=preview 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));
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.