Javascript 在画布中绘制裁剪的图像

Javascript 在画布中绘制裁剪的图像,javascript,Javascript,如何获得图像的正确位置,并将我在镜头中看到的东西绘制到画布上? 下面是我的示例和演示 var isDown, 镜头, img, 帆布, cx, 赛, ctx, 形象; img=document.getElementById('img'); lens=document.getElementById('lens'); canvas=document.getElementById('canvas'); cx=画布.offsetWidth/镜头.offsetWidth; cy=画布.偏视/镜头.偏视;

如何获得图像的正确位置,并将我在镜头中看到的东西绘制到画布上? 下面是我的示例和演示

var isDown,
镜头,
img,
帆布,
cx,
赛,
ctx,
形象;
img=document.getElementById('img');
lens=document.getElementById('lens');
canvas=document.getElementById('canvas');
cx=画布.offsetWidth/镜头.offsetWidth;
cy=画布.偏视/镜头.偏视;
ctx=canvas.getContext('2d');
图像=新图像();
image.src=img.src;
lens.addEventListener(“mousemove”,(e)=>{
活动透镜(e);
});
img.addEventListener(“mousemove”,(e)=>{
活动透镜(e);
});
功能镜头(e){
变量pos,x,y;
e、 预防默认值();
pos=getCursorPos(e);
x=位置x-(镜头偏移宽度/2);
y=位置y-(镜头离视/2);
如果(x>图像宽度-镜头偏移宽度){
x=img.width-lens.offsetWidth;
}
if(x<0){
x=0;
}
如果(y>图像高度-镜头离视){
y=图像高度-镜头离视;
}
if(y<0){
y=0;
}
lens.style.left=x+“px”;
lens.style.top=y+“px”;
绘制(x,y);
}
函数getCursorPos(e){
变量a,x=0,
y=0;
e=e | | window.event;
a=img.getBoundingClientRect();
x=e.pageX-a.左;
y=e.pageY-a.top;
x=x-window.pageXOffset;
y=y-window.pageYOffset;
返回{
x:x,
y:y
};
}
函数图(x,y){
ctx.drawImage(图像,x,y,canvas.width,canvas.height,0,0,canvas.width,canvas.height);
}
#容器{
位置:相对位置;
宽度:300px;
显示:内联块;
}
#容器>img{
最大宽度:100%;
}
#镜头{
位置:绝对位置;
边框:1px实心#d4;
宽度:80px;
高度:80px;
}

ctx.drawImage(图像、sx、sy、sWidth、SHIGHT、dx、dy、dWidth、DHHEIGHT)

根据源
图像测量
sx
sy
sWidth
sheigh
。假设我们有一张分辨率为高的图像,例如2000*1000,那么
sWidth
sHeight
应该放大到该分辨率。在您的情况下,
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);
}
ctx.drawImage(图像、sx、sy、sWidth、sHeight、dx、dy、dWidth、dHeight)

根据源
图像测量
sx
sy
sWidth
sheigh
。假设我们有一张分辨率为高的图像,例如2000*1000,那么
sWidth
sHeight
应该放大到该分辨率。在您的情况下,
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);
}