<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>淘宝放大镜</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
body {
font-size: 14px;
}
canvas {
display: none;
background-color: #f0f0f0;
}
#square {
width: 80px;
height: 80px;
background-color: rgba(117, 240, 255, 0.5);
position: absolute;
z-index: 999;
cursor: crosshair;
display: none;
}
</style>
</head>
<body>
<img src="images/a.jpg" width="300px" style="margin-left: 50px;">
<canvas id="canvas" width="200px" height="200px"></canvas>
<div id="square"></div>
<script>
onload = function() {
var canvas = document.getElementById("canvas"); //获取画布
var ctx = canvas.getContext("2d"); //获取画笔
var img = document.getElementsByTagName("img")[0]; //获取图片
var square = document.getElementById("square"); //获取选择框
var squareData = {}; //存选择框信息
var imgPosition = img.getBoundingClientRect(); //获取图片的位置
var p = img.naturalWidth / img.width; //原始图片与缩小后图片的比例
// console.log(img.naturalWidth, img.width)
console.log(imgPosition);
// 鼠标移入
img.onmouseove = function(e) {
var even = e || event; //兼容火狐浏览器
var x = even.clientX,
y = even.clientY;
createSquare(x, y);
};
window.onmousemove = function(e) {
var even = e || event;
// 获取鼠标的坐标
var x = even.clientX;
var y = even.clientY;
// console.log(x, y)
// 使选择框限制在图片内部
if (x >= img.offsetLeft && x <= img.offsetLeft + img.width && y >= img.offsetTop && y <= img.offsetTop + img.height) {
createSquare(x, y);
} else {
hideSquare();
hideCanvas();
}
};
function createSquare(x, y) {
x = x - 40 < img.offsetLeft ? img.offsetLeft : x - 40;
y = y - 40 < img.offsetTop ? img.offsetTop : y - 40;
x = x + 80 < imgPosition.right ? x : imgPosition.right - 80;
y = y + 80 < imgPosition.bottom ? y : imgPosition.bottom - 80;
// 将选择框左上角的位置存到squareData
squareData.left = x;
squareData.top = y;
// console.log(squareData)
moveSquare(x, y);
}
function moveSquare(x, y) {
// 设置选择框偏移位置
square.style.left = x + "px";
square.style.top = y + "px";
showCanvas();
showSquare();
draw();
}
function showCanvas() {
canvas.style.display = "inline";
}
function hideCanvas() {
canvas.style.display = "none";
}
function showSquare() {
square.style.display = "inline";
}
function hideSquare() {
square.style.display = "none";
}
// 将放大后的图片画到canvas中
function draw() {
var left = squareData.left - imgPosition.left;
var top = squareData.top - imgPosition.top;
// console.log(left, top)
// context.drawImage(img, sx, sy, swidth, sheight, x, y, width, height);
ctx.drawImage(img, left * p, top * p, p * 80, p * 80, 0, 0, canvas.width, canvas.height);
}
}
</script>
</body>
</html>
canvas实现淘宝放大镜效果
最新推荐文章于 2024-05-13 02:16:46 发布