js实现图片放大镜功能,简单明了
以下是一个简单的JavaScript图片放大镜实现示例:
HTML部分:
<div id="magnifier-container">
<img id="small-image" src="small-image.jpg" alt="小图" />
<div id="magnifier"></div>
</div>
CSS部分:
#magnifier-container {
position: relative;
display: inline-block;
}
#small-image {
width: 200px;
height: 200px;
}
#magnifier {
position: absolute;
width: 100px;
height: 100px;
background-color: rgba(255, 255, 0, 0.5);
display: none;
cursor: none;
z-index: 10;
}
JavaScript部分:
document.addEventListener('DOMContentLoaded', function() {
var container = document.getElementById('magnifier-container');
var smallImage = document.getElementById('small-image');
var magnifier = document.getElementById('magnifier');
container.addEventListener('mousemove', function(e) {
var offsetX = e.offsetX;
var offsetY = e.offsetY;
if (magnifier) {
magnifier.style.display = 'block';
magnifier.style.top = offsetY - magnifier.offsetHeight / 2 + 'px';
magnifier.style.left = offsetX - magnifier.offsetWidth / 2 + 'px';
var scaleFactor = 3; // 放大倍数
var xPos = offsetX - magnifier.offsetWidth / 2;
var yPos = offsetY - magnifier.offsetHeight / 2;
if (xPos < 0) xPos = 0;
if (yPos < 0) yPos = 0;
if (xPos > smallImage.width - magnifier.offsetWidth) xPos = smallImage.width - magnifier.offsetWidth;
if (yPos > smallImage.height - magnifier.offsetHeight) yPos = smallImage.height - magnifier.offsetHeight;
var largeWidth = smallImage.width * scaleFactor;
var largeHeight = smallImage.height * scaleFactor;
var largeX = xPos * scaleFactor - magnifier.offsetWidth / 2;
var largeY = yPos * scaleFactor - magnifier.offsetHeight / 2;
var largeImage = new Image();
largeImage.src = smallImage.src; // 假设放大的图片和原图一样,实际可能需要单独的大图
largeImage.onload = function() {
var context = document.createElement('canvas').getContext('2d');
context.drawImage(largeImage, largeX, largeY, magnifier.offsetWidth * scaleFactor, magnifier.offsetHeight * scaleFactor, 0, 0, magnifier.offsetWidth, magnifier.offsetHeight);
magnifier.style.backgroundImage = 'url(' + context.canvas.toDataURL('image/png') + ')';
};
}
});
container.addEventListener('mouseleave', function() {
if (magnifier) {
magnifier.style.display = 'none';
}
});
评论已关闭