我正在尝试在 Canvas 中显示上传图像的预览。预览应该是图像的方形版本。
我有:
var img = new Image;
img.src = imageSrc;
var c = document.getElementById('file-preview-' + data.response.id);
var ctx = c.getContext("2d");
img.onload = function() {
ctx.drawImage(img, 0, 0);
};
预览:
那么如何在 Canvas 上绘制一个 150x150 的正方形,并保持图像的比例裁剪版本?
例如这张图片:
我应该得到:
最佳答案
这是一种方法,可以精确地产生您想要的结果,裁剪、调整大小并居中(使用注释掉的行来产生基于左侧的裁剪)...
var ctx;
function init(event) {
ctx = document.getElementById('canvas').getContext('2d');
// Your preview is actually 120x120,
// but I've stuck with the textual description of
// your requirements here.
ctx.canvas.width = 150;
ctx.canvas.height = 150;
loadBackground('/image/PCKEo.png');
}
function loadBackground(path) {
var img = new Image();
img.onload = drawBackground;
img.src = path;
}
function drawBackground(event) {
var img = event.target;
var imgSize = Math.min(img.width, img.height);
// The following two lines yield a central based cropping.
// They can both be amended to be 0, if you wish it to be
// a left based cropped image.
var left = (img.width - imgSize) / 2;
var top = (img.height - imgSize) / 2;
//var left = 0; // If you wish left based cropping instead.
//var top = 0; // If you wish left based cropping instead.
ctx.drawImage(event.target, left, top, imgSize, imgSize, 0, 0, ctx.canvas.width, ctx.canvas.height);
}
window.addEventListener('load', init, false);
<canvas id="canvas"></canvas>
关于javascript - 在 Canvas 上绘制方形图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37868726/