原生js手撸拖拽矩形移动与缩放

一、写在前面

写这个原因很简单,有这么一个需求如下:

编写代码实现以下要求:画一个矩形,拖拽矩形的4个角可以将矩形缩放,在矩形上按住鼠标拖动可以移动该矩形的位置。
要求如下:

  1. 整个矩形的最小大小为 5px * 5px,缩放到最小时不能发生移动;
  2. 鼠标快速移动时移动和缩放效果要保持流畅。
    在这里插入图片描述
二、直接上代码

还是按照步骤一步一步的来吧。首先是要创建一个矩形,然后再写逻辑,下面一个矩形就画好了。。。
但是似乎屏幕上啥也没有。。 是的没宽高,所以就看不到了。别着急,继续画。

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>原生JS实现拖拽缩放元素</title>
    <style type="text/css">
        * {
            padding: 0;
            margin: 0;
        }

        #app-warpper {
            position: absolute;
            cursor: move;
        }
    </style>
</head>

<body>
    <div id="app-warpper"></div>
</body>
<script>
  //todo
</script>
</html>

这里开始写逻辑了,我们选择用类的形式来创建一个可以拖拽编辑的矩形。下面就是代码部分.若想看逻辑的可以一步一步的看代码注释,大概的思路就是,你需要计算你当前按下鼠标的位置,然后在移动的时候获取的鼠标位置与刚刚鼠标按下的位置进行一个计算.有个差值,这个差值就是需要移动的距离.

矩形缩放的时候就稍微要复杂一点了,大概思路如下:

  • 左上角缩放: 计算 left坐标,top的坐标,以及宽高;
  • 右上角缩放: 计算top坐标 和 宽高即可.
  • 右下角缩放: 计算宽高即可.
  • 左下角缩放: 计算left,top 和宽高.

可能描述有点抽象,但是动手写一遍的时候就知道大概是咋回事了.

  	/**
     * 创建一个可拖拽的矩形
     */
    function CreateDragRect(elm, options = {}) {
        if (!elm) throw new Error('el 必须是一个document对象');
        this.rect = elm;
        this.isLeftMove = true;
        this.isTopMove = true;
        this.rectDefaultPosition = options.position || 'fixed';
        this.rectDefaultLeft = options.x || 0;
        this.rectDefaultTop = options.y || 0;
        this.rectWidth = options.width || 100;
        this.rectHeight = options.height || 100;
        this.rectMinWidth = options.rectMinWidth || 5;  //最小宽度(超过之后不允许再缩放)
        this.rectMinHeight = options.rectMinHeight || 5;  //最小高度(超过之后不允许再缩放)
        this.rectBackgroundColor = options.background || '#ccc';
        this.dragIconSize = options.dragIconSize || '4px';
        this.dragIconColor = options.dragIconColor || '#f00';
        //主矩形是否可以移动
        this.isMove = false;
        this.initStyle();
        this.bindDragEvent(this.rect);
    }

    /**
     * 主矩形绑定move事件
     */
    CreateDragRect.prototype.bindDragEvent = function (dom, position) {
        const _this = this;
        dom.onmousedown = function (event) {
            event.stopPropagation();
            //按下矩形的时候可以移动,否则不可移动
            _this.isMove = !position;
            // 获取鼠标在wrapper中的位置
            let boxX = event.clientX - dom.offsetLeft;
            let boxY = event.clientY - dom.offsetTop;
            //鼠标移动事件(如果计算太高,有拖影)
            document.onmousemove = _this.throttle(function (moveEv) {
                let ev = moveEv || window.event;
                ev.stopPropagation();
                let moveX = ev.clientX - boxX;
                let moveY = ev.clientY - boxY;
                switch (position) {
                    case 'top-left':    //左上: 需计算top left width
                        _this.nwRectSize(moveX, moveY);
                        break;
                    case 'top-right':   //右上 计算top 和 height
                        _this.neRectSize(moveX, moveY);
                        break;
                    case 'right-bottom':  //只需计算当前鼠标位置
                        _this.seRectSize(moveX, moveY);
                        break;
                    case 'left-bottom': //计算left偏移量,计算w
                        _this.swRectSize(moveX, moveY);
                        break;
                    default:    //拖拽矩形
                        if (!_this.isMove) return null;
                        _this.moveRect(ev.clientX - boxX, ev.clientY - boxY);
                }
            }, 15);

            //鼠标松开,移除事件
            document.onmouseup = function (event) {
                document.onmousemove = null;
                document.onmouseup = null;
                // 存储当前的rect的宽高
                _this.rectWidth = _this.rect.offsetWidth;
                _this.rectHeight = _this.rect.offsetHeight;
                // 获得当前矩形的offsetLeft 和 offsetTop
                _this.rectOffsetLeft = _this.rect.offsetLeft;
                _this.rectOffsetTop = _this.rect.offsetTop;
            }
        }
    }

    /**
     * 初始化样式
     */
    CreateDragRect.prototype.initStyle = function () {
        this.rect.style.position = this.rectDefaultPosition;
        this.rect.style.width = this.rectWidth + 'px';
        this.rect.style.height = this.rectHeight + 'px';
        this.rect.style.left = this.rectDefaultLeft + 'px';
        this.rect.style.top = this.rectDefaultTop + 'px';
        this.rect.style.background = this.rectBackgroundColor;
        //依次为上 右 下 左
        let dragIcons = [
            {
                cursor: 'nw-resize',
                x: 'top',
                y: 'left'
            },
            {
                cursor: 'ne-resize',
                x: 'top',
                y: 'right'
            },
            {
                cursor: 'se-resize',
                x: 'right',
                y: 'bottom'
            },
            {
                cursor: 'sw-resize',
                x: 'left',
                y: 'bottom'
            }
        ];
        for (let i = 0, l = dragIcons.length; i < l; i++) {
            let icon = document.createElement('i');
            icon.id = Math.random().toString(36).substring(7);
            icon.style.display = 'inline-block';
            icon.style.width = this.dragIconSize;
            icon.style.height = this.dragIconSize;
            icon.style.position = 'absolute';
            icon.style.zIndex = 10;
            icon.style.cursor = dragIcons[i].cursor;
            icon.style.backgroundColor = this.dragIconColor;
            icon.style[dragIcons[i].x] = -parseInt(icon.style.width) / 2 + 'px';
            icon.style[dragIcons[i].y] = -parseInt(icon.style.height) / 2 + 'px';
            //绑定四个角的拖拽事件
            this.bindDragEvent(icon, `${dragIcons[i].x}-${dragIcons[i].y}`);
            //插入到矩形
            this.rect.appendChild(icon);
        }
    };

    /**
     * 移动主矩形
     */
    CreateDragRect.prototype.moveRect = function (x, y) {
        if (this.isTopMove && this.isLeftMove) {
            this.rect.style.left = x + 'px';
            this.rect.style.top = y + 'px';
        }
    };

    /**
     * 移动主矩形缩放 - 左上
     */
    CreateDragRect.prototype.nwRectSize = function (x, y) {
        //计算是否是最小宽度
        const { width, height, isLeftMove, isTopMove } = this.getMinSize(this.rectWidth - x, this.rectHeight - y);
        if (isTopMove) {
            this.rect.style.top = this.rectOffsetTop + y + 'px';
            this.rect.style.height = height + 'px';
        }
        if (isLeftMove) {
            this.rect.style.left = this.rectOffsetLeft + x + 'px';
            this.rect.style.width = width + 'px';
        }
    };

    /**
     * 移动主矩形缩放 - 左下
     */
    CreateDragRect.prototype.swRectSize = function (x, y) {
        //计算是否是最小宽度
        const { width, height, isLeftMove, isTopMove } = this.getMinSize(this.rectWidth - x, y);
        if (isLeftMove) {
            this.rect.style.left = this.rectOffsetLeft + x + 'px';
            this.rect.style.width = width + 'px';
        }
        if (isTopMove) {
            this.rect.style.height = height + 'px';
        }
    };

    /**
     * 移动主矩形缩放 - 右上
     */
    CreateDragRect.prototype.neRectSize = function (x, y) {
        //计算是否是最小宽度
        const { width, height, isTopMove, isLeftMove } = this.getMinSize(x, this.rectHeight - y);
        if (isTopMove) {
            this.rect.style.height = height + 'px';
            this.rect.style.top = this.rectOffsetTop + y + 'px';
        }
        if (isLeftMove) {
            this.rect.style.width = width + 'px';
        }
    };

    /**
     * 移动主矩形缩放 - 右下
     */
    CreateDragRect.prototype.seRectSize = function (x, y) {
        //计算是否是最小宽度
        const { width, height } = this.getMinSize(x, y);
        this.rect.style.width = width + 'px';
        this.rect.style.height = height + 'px';
    };

    /**
    * 节流函数
    * @param {*} fn 
    * @param {*} delay 
    */
    CreateDragRect.prototype.throttle = function (fn, delay) {
        let last = 0;
        return function () {
            let curr = Date.now();
            if (curr - last > delay) {
                fn.apply(this, arguments);
                last = curr;
            }
        }
    }

    /**
     * 获取宽高
     * @param {*} w 
     * @param {*} h 
     * @return { Object }
     */
    CreateDragRect.prototype.getMinSize = function (w, h) {
        let rectMinWidth = this.rectMinWidth;
        let rectMinHeight = this.rectMinHeight;
        //x拖拽
        this.isLeftMove = w >= this.rectMinWidth;
        //y拖拽
        this.isTopMove = h >= this.rectMinHeight;
        if (this.isLeftMove) rectMinWidth = w;
        if (this.isTopMove) rectMinHeight = h;
        return { width: rectMinWidth, height: rectMinHeight, isLeftMove: this.isLeftMove, isTopMove: this.isTopMove };
    }
三、完整代码

只想用代码功能的,只需要复制到你的html文件中就可以直接使用了.

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>原生JS实现拖拽缩放元素</title>
    <style type="text/css">
        * {
            padding: 0;
            margin: 0;
        }

        #app-warpper {
            position: absolute;
            cursor: move;
        }
    </style>
</head>

<body>
    <div id="app-warpper"></div>
</body>
<script>
		/**
		 * 创建一个可拖拽的矩形
		 */
		function CreateDragRect(elm, options = {}) {
			if (!elm) throw new Error('el 必须是一个document对象');
			this.rect = elm;
			this.isLeftMove = true;
			this.isTopMove = true;
			this.rectDefaultPosition = options.position || 'fixed';
			this.rectDefaultLeft = options.x || 0;
			this.rectDefaultTop = options.y || 0;
			this.rectWidth = options.width || 100;
			this.rectHeight = options.height || 100;
			this.rectMinWidth = options.rectMinWidth || 5;  //最小宽度(超过之后不允许再缩放)
			this.rectMinHeight = options.rectMinHeight || 5;  //最小高度(超过之后不允许再缩放)
			this.rectBackgroundColor = options.background || '#ccc';
			this.dragIconSize = options.dragIconSize || '4px';
			this.dragIconColor = options.dragIconColor || '#f00';
			//主矩形是否可以移动
			this.isMove = false;
			this.initStyle();
			this.bindDragEvent(this.rect);
		}

		/**
		 * 主矩形绑定move事件
		 */
		CreateDragRect.prototype.bindDragEvent = function (dom, position) {
			const _this = this;
			dom.onmousedown = function (event) {
				event.stopPropagation();
				//按下矩形的时候可以移动,否则不可移动
				_this.isMove = !position;
				// 获取鼠标在wrapper中的位置
				let boxX = event.clientX - dom.offsetLeft;
				let boxY = event.clientY - dom.offsetTop;
				//鼠标移动事件(如果计算太高,有拖影)
				document.onmousemove = _this.throttle(function (moveEv) {
					let ev = moveEv || window.event;
					ev.stopPropagation();
					let moveX = ev.clientX - boxX;
					let moveY = ev.clientY - boxY;
					switch (position) {
						case 'top-left':    //左上: 需计算top left width
							_this.nwRectSize(moveX, moveY);
							break;
						case 'top-right':   //右上 计算top 和 height
							_this.neRectSize(moveX, moveY);
							break;
						case 'right-bottom':  //只需计算当前鼠标位置
							_this.seRectSize(moveX, moveY);
							break;
						case 'left-bottom': //计算left偏移量,计算w
							_this.swRectSize(moveX, moveY);
							break;
						default:    //拖拽矩形
							if (!_this.isMove) return null;
							_this.moveRect(ev.clientX - boxX, ev.clientY - boxY);
					}
				}, 15);

				//鼠标松开,移除事件
				document.onmouseup = function (event) {
					document.onmousemove = null;
					document.onmouseup = null;
					// 存储当前的rect的宽高
					_this.rectWidth = _this.rect.offsetWidth;
					_this.rectHeight = _this.rect.offsetHeight;
					// 获得当前矩形的offsetLeft 和 offsetTop
					_this.rectOffsetLeft = _this.rect.offsetLeft;
					_this.rectOffsetTop = _this.rect.offsetTop;
				}
			}
		}

		/**
		 * 初始化样式
		 */
		CreateDragRect.prototype.initStyle = function () {
			this.rect.style.position = this.rectDefaultPosition;
			this.rect.style.width = this.rectWidth + 'px';
			this.rect.style.height = this.rectHeight + 'px';
			this.rect.style.left = this.rectDefaultLeft + 'px';
			this.rect.style.top = this.rectDefaultTop + 'px';
			this.rect.style.background = this.rectBackgroundColor;
			//依次为上 右 下 左
			let dragIcons = [
				{
					cursor: 'nw-resize',
					x: 'top',
					y: 'left'
				},
				{
					cursor: 'ne-resize',
					x: 'top',
					y: 'right'
				},
				{
					cursor: 'se-resize',
					x: 'right',
					y: 'bottom'
				},
				{
					cursor: 'sw-resize',
					x: 'left',
					y: 'bottom'
				}
			];
			for (let i = 0, l = dragIcons.length; i < l; i++) {
				let icon = document.createElement('i');
				icon.id = Math.random().toString(36).substring(7);
				icon.style.display = 'inline-block';
				icon.style.width = this.dragIconSize;
				icon.style.height = this.dragIconSize;
				icon.style.position = 'absolute';
				icon.style.zIndex = 10;
				icon.style.cursor = dragIcons[i].cursor;
				icon.style.backgroundColor = this.dragIconColor;
				icon.style[dragIcons[i].x] = -parseInt(icon.style.width) / 2 + 'px';
				icon.style[dragIcons[i].y] = -parseInt(icon.style.height) / 2 + 'px';
				//绑定四个角的拖拽事件
				this.bindDragEvent(icon, `${dragIcons[i].x}-${dragIcons[i].y}`);
				//插入到矩形
				this.rect.appendChild(icon);
			}
		};

		/**
		 * 移动主矩形
		 */
		CreateDragRect.prototype.moveRect = function (x, y) {
			if (this.isTopMove && this.isLeftMove) {
				this.rect.style.left = x + 'px';
				this.rect.style.top = y + 'px';
			}
		};

		/**
		 * 移动主矩形缩放 - 左上
		 */
		CreateDragRect.prototype.nwRectSize = function (x, y) {
			//计算是否是最小宽度
			const { width, height, isLeftMove, isTopMove } = this.getMinSize(this.rectWidth - x, this.rectHeight - y);
			if (isTopMove) {
				this.rect.style.top = this.rectOffsetTop + y + 'px';
				this.rect.style.height = height + 'px';
			}
			if (isLeftMove) {
				this.rect.style.left = this.rectOffsetLeft + x + 'px';
				this.rect.style.width = width + 'px';
			}
		};

		/**
		 * 移动主矩形缩放 - 左下
		 */
		CreateDragRect.prototype.swRectSize = function (x, y) {
			//计算是否是最小宽度
			const { width, height, isLeftMove, isTopMove } = this.getMinSize(this.rectWidth - x, y);
			if (isLeftMove) {
				this.rect.style.left = this.rectOffsetLeft + x + 'px';
				this.rect.style.width = width + 'px';
			}
			if (isTopMove) {
				this.rect.style.height = height + 'px';
			}
		};

		/**
		 * 移动主矩形缩放 - 右上
		 */
		CreateDragRect.prototype.neRectSize = function (x, y) {
			//计算是否是最小宽度
			const { width, height, isTopMove, isLeftMove } = this.getMinSize(x, this.rectHeight - y);
			if (isTopMove) {
				this.rect.style.height = height + 'px';
				this.rect.style.top = this.rectOffsetTop + y + 'px';
			}
			if (isLeftMove) {
				this.rect.style.width = width + 'px';
			}
		};

		/**
		 * 移动主矩形缩放 - 右下
		 */
		CreateDragRect.prototype.seRectSize = function (x, y) {
			//计算是否是最小宽度
			const { width, height } = this.getMinSize(x, y);
			this.rect.style.width = width + 'px';
			this.rect.style.height = height + 'px';
		};

		/**
		* 节流函数
		* @param {*} fn 
		* @param {*} delay 
		*/
		CreateDragRect.prototype.throttle = function (fn, delay) {
			let last = 0;
			return function () {
				let curr = Date.now();
				if (curr - last > delay) {
					fn.apply(this, arguments);
					last = curr;
				}
			}
		}

		/**
		 * 获取宽高
		 * @param {*} w 
		 * @param {*} h 
		 * @return { Object }
		 */
		CreateDragRect.prototype.getMinSize = function (w, h) {
			let rectMinWidth = this.rectMinWidth;
			let rectMinHeight = this.rectMinHeight;
			//x拖拽
			this.isLeftMove = w >= this.rectMinWidth;
			//y拖拽
			this.isTopMove = h >= this.rectMinHeight;
			if (this.isLeftMove) rectMinWidth = w;
			if (this.isTopMove) rectMinHeight = h;
			return { width: rectMinWidth, height: rectMinHeight, isLeftMove: this.isLeftMove, isTopMove: this.isTopMove };
		}
		const dr = new CreateDragRect(document.getElementById('app-warpper'), {
			x: 500,
			y: 300,
			width: 300,
			height: 300,
		});
</script>

</html>

四、写在后面

上面就是原生js创建一个可拖拽缩放矩形功能的全部内容了,加油,快动手试试吧。

若学习,只需要看懂代码核心部分即可,可以忽略无关紧要的部分,有问题请留言或者@博主,谢谢支持o( ̄︶ ̄)o~

感谢您的阅读,如果此文章或项目对您有帮助,请给个一键三连吧,GitHub有开源项目,需要的小伙伴可以顺手star一下!

GitHub: https://github.com/langyuxiansheng

更多信息请关注公众号: “笔优站长”

笔优站长

扫码关注“笔优站长”,支持站长
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

狼丶宇先森

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

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

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

打赏作者

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

抵扣说明:

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

余额充值