本帖最后由 马黑黑 于 2024-4-10 14:03 编辑
一楼,图片会被缩小一半显示。以下提供的代码则是按图片原始尺寸显示,可将代码存为本地HTML文档测试:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>放大镜</title>
<meta name="author" content="" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<style>
#wrapper { margin: 20px auto; width: fit-content; height: fit-content; position: relative; }
#canv { position: absolute; transform: scale(var(--size)); border-radius: 50%; pointer-events: none; --size: 1; }
</style>
</head>
<body>
<div id="wrapper">
<img id="img1" src="https://img.zcool.cn/community/01e8bf5c00a77aa801209252bda875.jpg@1280w_1l_2o_100sh.jpg" alt="" />
<canvas id="canv" width="200" height="200"></canvas>
</div>
<script type="text/javascript">
let ww, hh, beShown = false, mTimer;
let ctx = canv.getContext('2d');
let getSize = (img) => {
ww = img.width;
hh = img.height;
};
img1.onload = (callback) => getSize(img1);
img1.onmousemove = (e) => {
clearTimeout(mTimer);
img1.style.cursor = 'crosshair';
let x = e.offsetX, y = e.offsetY;
if(x - 25 < 0) x = 25;
if(ww - x < 25) x = ww - 25;
if(y - 25 < 0) y = 25;
if(hh - y < 25) y = hh - 25;
canv.style.left = x - 100 + 'px';
canv.style.top = y - 100 + 'px';
ctx.clearRect(0, 0, 200, 200);
ctx.drawImage(img1, x - 25, y - 25, 50, 50, 0, 0, 200, 200);
mTimer = setTimeout('ctx.clearRect(0, 0, 200, 200)', 1000);
};
</script>
</body>
</html>
|