JavaScript实战练习——图片裁剪

源码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            margin: 0;
            padding: 0;
        }
        #app {
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <div id="app"></div>

    <script src="/通用资源/publicPackage.js"></script>
    <script>
        var app = document.getElementById('app');
        dealImage(app, '/img/small.jpg');

        function dealImage(dom, url) {
            //创建图片
            var img = new Image();
            //设置图片地址
            img.src = url;
            //图片加载完毕
            img.onload = function () {
                var width = img.width;
                var height = img.height;
                // console.log(img.width, img.height);
                //创建遮罩层
                var layer = document.createElement('div');
                //创建切图层
                var mask = document.createElement('div');
                //创建小圆点
                var dot = document.createElement('div');
                dom.appendChild(layer);
                dom.appendChild(mask);
                mask.appendChild(dot);
                css(dom, {
                    width: width + 'px',
                    height: height + 'px',
                    backgroundImage: 'url(' + url + ')',
                    position: 'relative',
                    border: '1px solid #ccc'
                });
                css(layer, {
                    position: 'absolute',
                    left: 0,
                    top: 0 ,
                    right: 0,
                    bottom: 0,
                    backgroundColor: 'rgba(0, 0, 0, 0.4)'
                });
                css(mask, {
                    width: width / 4 + 'px',
                    height: height / 4 + 'px',
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    backgroundImage: 'url(' + url + ')',
                    cursor: 'move'
                });
                css(dot, {
                    width: '10px',
                    height: '10px',
                    position: 'absolute',
                    right: '-5px',
                    bottom: '-5px',
                    borderRadius: '50%',
                    backgroundColor: 'red',
                    cursor: 'default'
                });
                var ox, oy, top, left, maskLeft, maskTop;
                //dot交互
                function moveDot(e) {
                    //鼠标移动时位置
                    var dx = e.clientX;
                    var dy = e.clientY;
                    //新坐标
                    var x = dx - ox + left;
                    var y = dy - oy + top;
                    //边界处理
                    if (x < 0) {
                        x = 0;
                    } else if (x + maskLeft > width) {
                        x = width - maskLeft;
                    };
                    if (y < 0) {
                        y = 0;
                    } else if (y + maskTop > height) {
                        y = height - maskTop;
                    };
                    css(mask, {
                        width: x + 'px',
                        height: y + 'px'
                    });
                };
                bindEvent(dot, 'mousedown', function(e) {
                    //停止冒泡
                    e.stopPropagation();
                    //鼠标点击时位置
                    ox = e.clientX;
                    oy = e.clientY;
                    //mask宽高
                    left = parseInt(getStyle(mask, 'width'));
                    top = parseInt(getStyle(mask, 'height'));
                    //mask原先偏移量
                    maskLeft = mask.offsetLeft;
                    maskTop = mask.offsetTop;
                    bindEvent(document, 'mousemove', moveDot);
                });
                bindEvent(document, 'mouseup', function(e) {
                    removeEvent(document, 'mousemove', moveDot);
                });
                //mask交互
                function moveMask(e) {
                    //鼠标移动时位置
                    var dx = e.clientX;
                    var dy = e.clientY;
                    //移动距离
                    var x = dx - mx + ml;
                    //边界处理
                    var y = dy - my + mt;
                    if (x < 0) {
                        x = 0;
                    } else if (x + mw > width) {
                        x = width - mw;
                    };
                    if (y < 0) {
                        y = 0;
                    } else if (y + mh > height) {
                        y = height - mh;
                    };
                    css(mask, {
                    backgroundPositionX: -x + 'px',
                    backgroundPositionY: -y + 'px',
                    left: x + 'px',
                    top: y + 'px'
                });
                };
                bindEvent(mask, 'mousedown', function(e) {
                    //鼠标点击时位置
                    mx = e.clientX;
                    my = e.clientY;
                    //mask宽高
                    mw = parseInt(getStyle(mask, 'width'));
                    mh = parseInt(getStyle(mask, 'height'));
                    //mask原先偏移量
                    ml = mask.offsetLeft;
                    mt = mask.offsetTop;
                    bindEvent(document, 'mousemove', moveMask);
                });
                bindEvent(document, 'mouseup', function() {
                    removeEvent(document, 'mousemove', moveMask);
                });
            };
        };
    </script>
</body>
</html>

publicPackage.js文件是我自己日常封装的一些方法,这次的实战练习中也有用到getStyle()、removeEvent()、bindEvent()等自己封装的方法(只要你没见过就是我自定义的,别怀疑你自己的小脑瓜子),这次的dealImage()也可以封装好,下次直接调用。这里奉上publicPackage.js文件里面的全部代码。

publicPackage.js

/***
获取任何元素样式
    @element    元素
    @styleName  样式
***/ 
function getStyle(element, styleName) {
    if (window.getComputedStyle) {
        return getComputedStyle(element)[styleName];
    } else{
        var style= element.currentStyle;
        if (style) {
            styleName = styleName.replace(/-([a-z])?/g, function(match, $1) {
                return $1.toUpperCase();
            })
            return style[styleName];
        };
    };
};

/***
实现任何事件绑定(DOM0、DOM2、ie)
    @dom    元素
    @type   事件
    @fn     回调函数
***/ 
function bindEvent(dom, type, fn) {
    if (dom.addEventListener) {
        dom.addEventListener(type, fn);
    } else if (dom.attachEvent) {
        dom.attachEvent('on' + type, function(e) {
            e.target = e.srcElement;
            e.currentTarget = this;
            fn.call(dom, e);    //this指向
        });
    } else {
        var oldFun = dom['on' + type];
        dom['on' + type] = function(e) {
            oldFun && oldFun(e || window.event);
            fn(e || window.event);
        };
    };
};

/***
实现任何事件移除(DOM0、DOM2、ie)
    @dom    元素
    @type   事件
    @fn     回调函数
***/ 
function removeEvent(dom, type, fn) {
    if (dom.removeEventListener) {
        dom.removeEventListener(type, fn);
    } else if (dom.detachEvent) {
        dom.detachEvent('on' + type, fn);
    } else {
        dom['on' + type] = null;
    }
}

/***
封装防抖函数
    @fn     函数
***/ 
function throttle_event(fn) {
    clearTimeout(fn.__timebar);
    fn.__timebar = setTimeout(fn, 200);
};

/***
封装节流函数
    @fn     函数
***/ 
function throttle_time(fn) {
    //lock为true不执行
    if (fn.__lock) {
        return;
    };
    fn.__lock = true;
    fn();
    setTimeout(function() {
        fn.__lock = false;
    },1000);
};

/***
实现设置样式方法 css(dom, width, 200px) 或 css(dom, {width: '200px', color: 'red'})
    @dom    元素
    @key   样式名
    @value     样式值
***/ 
function css(dom, key, value) {
    if (typeof key === 'string') {
        dom.style[key] = value;
    } else {
        for (var name in key) {
            css(dom, name, key[name]);
        }
    }
}

/***
实现任何元素到document的距离
    @dom    元素
***/ 
function offset(dom) {
    var result = {
        left: dom.offsetLeft,
        top: dom.offsetTop
    };
    while (dom !== document.getElementsByTagName('body')[0]) {
        dom = dom.offsetParent;
        result.left += dom.offsetLeft + dom.clientLeft;
        result.top += dom.offsetTop + dom.clientTop;
    }
    return result;
};

/***
封装放大器方法
    @dom    元素
    @url    图片地址
    @width  容器宽度
    @height 容器高度
***/ 
function imageZoom(dom, url, width, height) {
    var mask = document.createElement('div');
    var big = document.createElement('div');
    app.appendChild(mask);
    app.appendChild(big);
    css(app, {
        width: width + 'px',
        height: height + 'px',
        position: 'relative',
        backgroundImage: 'url('+ url +')',
        backgroundSize: 'cover',
        backgroundRepeat: 'no-repeat',
        border: '1px solid #ccc'
    });
    css(mask, {
        width: width / 2 + 'px',
        height: height / 2 + 'px',
        position: 'absolute',
        backgroundColor: 'rgba(214, 235, 99, 0.4)',
        cursor: 'move',
        display: 'none'
    });
    css(big, {
        width: width + 'px',
        height: height + 'px',
        position: 'absolute',
        top: 0,
        left: '100%',
        backgroundImage: 'url('+ url +')',
        backgroundRepeat: 'no-repeat',
        display: 'none'
    });
    //鼠标移入
    bindEvent(app, 'mouseenter', function(e) {
        //鼠标进入时位置
        //mask和big显示
        css(mask, {display: 'block'});
        css(big, {display: 'block'});
        //鼠标移动时位置
        bindEvent(dom, 'mousemove', function(e) {
            var mouse_newX = e.clientX;
            var mouse_newY = e.clientY;
            //mask左顶点位置
            var mask_left = mouse_newX - width / 4 - offset(dom)['left'] + document.documentElement.scrollLeft;
            var mask_top = mouse_newY - height /4 - offset(dom)['top'] + document.documentElement.scrollTop;
            //边界处理(mask始终不能跑到app外头)
            if (mask_left < 0) {
                mask_left = 0;
            } else if (mask_left > width / 2) {
                mask_left = width / 2;
            };
            if(mask_top < 0) {
                mask_top = 0;
            } else if (mask_top > height / 2) {
                mask_top = height / 2;
            }
            //mask位置(mask随鼠标移动而移动)
            css(mask, {left: mask_left + 'px', top: mask_top + 'px'});
            console.log(mask_left, mask_top);
            //big背景图设置
            css(big, {
                backgroundPositionX: '-' + mask_left * 2 + 'px',
                backgroundPositionY: '-' + mask_top * 2 + 'px',
            })
        });
    });
    // 鼠标移出
    bindEvent(app, 'mouseleave', function(e) {
        css(mask, {display: 'none'});
        css(big, {display: 'none'});
    }); 
};

效果演示:

javaScript实战——图片裁剪

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

邻家的肥猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值