gpt4 book ai didi

javascript - 在 Canvas 中绘制方形版本的图像

转载 作者:太空宇宙 更新时间:2023-11-04 16:06:26 27 4
gpt4 key购买 nike

我正在尝试在 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);
};

预览:

enter image description here

那么我如何在 Canvas 上绘制一个 150x150 的正方形并保持图像的裁剪版本?

例如这张图片:

enter image description here

我应该得到:

enter image description here

最佳答案

这里有一种方法可以精确地产生您想要的结果、裁剪、调整大小和居中(注释掉的行产生左基裁剪)...

    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('http://i.stack.imgur.com/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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com