gpt4 book ai didi

javascript - 图像对象裁剪并在 Canvas 中心绘制

转载 作者:行者123 更新时间:2023-11-30 08:40:45 26 4
gpt4 key购买 nike

如何裁剪图像,然后将其绘制在 Canvas 的中央?

目前我有一个放置 div,我可以在其中放置图像,然后由 JavaScript 拾取图像。然后我想让 JavaScript 检查哪个更高(高度或宽度)。如果高度最高,我希望它是 200px 并且宽度要根据纵横比进行调整。之后,我希望 JavaScript 在 Canvas 中绘制图像,图像的中心就是 Canvas 的中心。

我现有的代码无法正常工作(我不确定为什么):

(为简单起见,我只是将网络上的图像传递给函数)

render('http://www.aboveandbeyond.nu/sites/www.aboveandbeyond.nu/files/news/europe_above_beyond_tour.jpg');



function render(src){

var image = new Image();
var canvas = document.getElementById("artworkcanvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
image.onload = function(){

var sourceX = 200;
var sourceY = 0;
var sourceWidth = 200;
var sourceHeight = 200;
var destWidth = sourceWidth;
var destHeight = sourceHeight;
var destX = canvas.width / 2 - destWidth / 2;
var destX = 0;
var destY = canvas.height / 2 - destHeight / 2;
var destY = 0;
var MAX_WIDTH = 200;
var MAX_HEIGHT = 200;

if (image.height == image.width) {
image.width = MAX_WIDTH;
image.height = MAX_HEIGHT;
} else {
if(image.height < image.width) {
console.log("height smaller");
image.width *= MAX_HEIGHT / image.height;
image.height = MAX_HEIGHT;
} else {
image.height *= MAX_WIDTH / image.width;
image.width = MAX_WIDTH;
}
}

ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas.width = image.width;
canvas.height = image.height;

ctx.drawImage(image, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
};

image.src = src;

最佳答案

这是在保持纵横比的同时使用缩放版本的 drawImage 的一种方法:

  // calc scale that fits into 200x200 and also maintains aspect ratio
var scale=Math.min((MAX_WIDTH/img.width),(MAX_HEIGHT/img.height));

ctx.drawImage(img,
0,0,img.width,img.height,
(canvas.width-img.width*scale)/2, (canvas.height-img.height*scale)/2,
img.width*scale, img.height*scale
);

enter image description here

示例代码和演示:

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.src="http://www.aboveandbeyond.nu/sites/www.aboveandbeyond.nu/files/news/europe_above_beyond_tour.jpg";
function start(){

var MAX_WIDTH = 200;
var MAX_HEIGHT = 200;
var iw=img.width;
var ih=img.height;

// calc scale that fits into 200x200 and also maintains aspect ratio
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
);

}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>

关于javascript - 图像对象裁剪并在 Canvas 中心绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26705803/

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