当您将鼠标悬停在图像上时,我想在画布上显示图像的放大视图。因此,我有一个<img>
标记,它被设置为100%的宽度和高度。
这是我写的代码-
<!DOCTYPE html>
<html>
<head>
<title>sdfsdf</title>
</head>
<style type="text/css">
* {
padding: 0px;
height: 0px;
}
.overlay {
position: fixed;
z-index: 1000000000;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: block;
cursor: crosshair;
overflow: hidden;
background: black;
}
.overlay img {
width: 100%;
height: 100%;
}
canvas {
position: absolute;
bottom: 0;
right: 0;
width: 180px;
height: 140px;
border: 1px solid red;
}
</style>
<body>
<div class="overlay">
<img src="test.png" id="img"/>
<canvas id="canvas"><canvas>
</div>
</body>
<script type="text/javascript">
const scale = 10;
const canvas = document.getElementById("canvas");
const img = document.getElementById("img");
canvas.width = 180;
canvas.height = 140;
const context = canvas.getContext('2d');
context.imageSmoothingEnabled = false;
let mx = 0, my = 0;
img.addEventListener("mousemove", event =>
{
mx = event.clientX;
my = event.clientY;
});
const image = new Image();
function loop()
{
context.clearRect(0, 0, canvas.width, canvas.height);
const imgX = - mx * scale + canvas.width / 2;
const imgY = - my * scale + canvas.height / 2;
const imageWidth = image.width * scale;
const imageHeight = image.height * scale;
context.drawImage(image,
imgX,
imgY,
imageWidth,
imageHeight);
requestAnimationFrame(loop);
}
image.onload = () =>
{
requestAnimationFrame(loop);
}
image.src = "test.png";
</script>
</html>
这很好,并且图像在画布中居中。但是,当页面放大/缩小并且图像从不居中并且存在怪异的偏移时,这会中断。我尝试了一堆东西来补偿偏移量,但是它们都不应该完美工作。
谢谢!