gpt4 book ai didi

javascript - 在 Canvas 中绘制裁剪后的图像

转载 作者:行者123 更新时间:2023-11-30 09:15:38 25 4
gpt4 key购买 nike

如何获取图像的正确位置并将我在镜头中看到的内容绘制到 Canvas 中?这是我的演示示例。

var isDown,
lens,
img,
canvas,
cx,
cy,
ctx,
image;

img = document.getElementById('img');
lens = document.getElementById('lens');
canvas = document.getElementById('canvas');
cx = canvas.offsetWidth / lens.offsetWidth;
cy = canvas.offsetHeight / lens.offsetHeight;

ctx = canvas.getContext('2d');
image = new Image();
image.src = img.src;

lens.addEventListener("mousemove", (e) => {
moveLens(e);
});

img.addEventListener("mousemove", (e) => {
moveLens(e);
});


function moveLens(e) {
var pos, x, y;
e.preventDefault();
pos = getCursorPos(e);
x = pos.x - (lens.offsetWidth / 2);
y = pos.y - (lens.offsetHeight / 2);
if (x > img.width - lens.offsetWidth) {
x = img.width - lens.offsetWidth;
}
if (x < 0) {
x = 0;
}
if (y > img.height - lens.offsetHeight) {
y = img.height - lens.offsetHeight;
}
if (y < 0) {
y = 0;
}
lens.style.left = x + "px";
lens.style.top = y + "px";
draw(x, y);
}

function getCursorPos(e) {
var a, x = 0,
y = 0;
e = e || window.event;
a = img.getBoundingClientRect();
x = e.pageX - a.left;
y = e.pageY - a.top;
x = x - window.pageXOffset;
y = y - window.pageYOffset;
return {
x: x,
y: y
};
}

function draw(x, y) {
ctx.drawImage(image, x, y, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);
}
#container {
position: relative;
width: 300px;
display:inline-block;
}

#container>img {
max-width: 100%;
}

#lens {
position: absolute;
border: 1px solid #d4d4d4;
width: 80px;
height: 80px;
}
<div id="container">
<div id="lens"></div>
<img src="https://cdn.pixabay.com/photo/2016/06/18/17/42/image-1465348_960_720.jpg" id="img">
</div>
<canvas width="200" height="200" id="canvas"></canvas>

最佳答案

ctx.drawImage(图像, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

sx,sy,sWidth,sHeight是根据源码image<测量的。假设我们有一张HIGH 分辨率的图像,例如 2000 * 1000,那么 sWidthsHeight 应该按比例放大到该分辨率.在您的情况下,sWidth 应为 80/300 * 2000。

我已经对您的代码进行了这些调整。

function draw(x, y) {
ctx.clearRect(0, 0, canvas.width, canvas.height); // you might want to draw on a clean canvas each time
let scaleX = x / img.offsetWidth * image.width;
let scaleY = y / img.offsetHeight * image.height;
let scaleWidth = lens.offsetWidth / img.width * image.width;
let scaleHeight = lens.offsetHeight / img.height * image.height;
ctx.drawImage(image, scaleX, scaleY, scaleWidth, scaleHeight, 0, 0, canvas.width, canvas.height);
}

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

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