图片的局部放大算法

如下图所示:

下面是完整代码,算法的每一步已加注释


<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>局部放大title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        section {
            float: left;
        }

        #small {
            position: relative;
        }

        span {
            width: 150px;
            height: 150px;
            background-color: rgba(255, 255, 255, .3);
            position: absolute;
            display: none;
            cursor: move;
        }

        div {
            float: left;
            margin-left: 1px;
        }

        #big {
            width: 300px;
            height: 300px;
            border: 1px solid pink;
            overflow: hidden;
            display: none;
        }

        #box {
            margin-top: 100px;
            margin-left: 100px;
        }
    style>
head>
<body>
<div id="box">
    <div id="small">
        <img src="../untitled/7.jpg" alt="" id="im0"/>
        <span id="sp">span>
    div>
    <div id="big">
        <img src="../untitled/7.jpg" alt="" width="900" id="im"/>
    div>
div>
<script src="common.js">script>
<script>
    //获取需要的元素
    var box = my$("box");
    //获取小图的div
    var small = box.children[0];
    //获取遮挡层
    var mask = small.children[1];
    //获取大图
    var big = box.children[1];
    //鼠标进入显示遮挡层和大图div
    box.onmouseover = function () {
        mask.style.display = "block";
        big.style.display = "block";
    };
    //鼠标离开隐藏遮挡层和大图的div
    box.onmouseout = function () {
        mask.style.display = "none";
        big.style.display = "none";
    };
    small.onmousemove = function (e) {
        //鼠标此时的可视区域的横坐标和纵坐标
        var x = e.clientX + mask.offsetWidth / 2;
        var y = e.clientY + mask.offsetTop / 2;
        //为遮挡层的left和top赋值
        x = x - 250;
        y = y - 200;
        //遮挡层横坐标最小值
        x = x < 0 ? 0 : x;
        //遮挡层纵坐标最小值
        y = y < 0 ? 0 : y;
        //遮挡层横坐标的最大值
        x = x > small.offsetWidth - mask.offsetWidth ? small.offsetWidth - mask.offsetWidth : x;
        //遮挡层纵坐标的最大值
        y = y > small.offsetHeight - mask.offsetHeight ? small.offsetHeight - mask.offsetHeight : y;
        mask.style.left = x + "px";
        mask.style.top = y + "px";
        //遮挡层的移动距离 / 大图的移动距离 = 遮挡层的最大移动距离 / 大图的最大移动距离
        //大图的移动距离 = 遮挡层的移动距离 * 大图的最大移动距离 / 遮挡层的最大移动距离

        //大图的横向的最大移动距离
        var maxX = my$("im").offsetWidth - big.offsetWidth;
        //大图的纵向的最大移动距离
        var maxY = my$("im").offsetHeight - big.offsetHeight;

        //大图和小图的宽度的比例
        var pro = my$("im").offsetWidth / my$("im0").offsetWidth;
        //大图的横向移动坐标
        var bigImMoveX = x * pro;//maxX / ( small.offsetWidth - mask.offsetWidth);
        var bigImMoveY = y * pro;//maxY / ( small.offsetWidth - mask.offsetWidth);
        //设置图片移动
        my$("im").style.marginLeft = -bigImMoveX + "px";
        my$("im").style.marginTop = -bigImMoveY + "px";
    };
script>
body>
html>

你可能感兴趣的:(js)