js如何实现一个new方法

JavaScript014

js如何实现一个new方法,第1张

首先我们先要了解new的原理

由此可以看出在new的过程中会将函数执行,并且创建一个对象 且可以通过原型链调用构造函数的原型方法,最后返回该实例

由此可以简单实现出

因为需要计算元素的位置变化,所以需要掌握几个关于位置的api

点击需要拖动元素时,获取该元素的初始位置。

鼠标移动期间 获取元素当前的位置信息

计算

进行事件监听

拖拽的实现原理:通过事件mousedown(事件的触发) →mousemove(事件的控制) →mouseup(事件的清除),拖拽的过程就是mousemove阶段;

问题产生的原因:因为mousemove 的间隔性触发,当两次mousemove事件触发的间隔中,鼠标移动距离出了element的范围,就会产生鼠标脱离element范围,拖拽就停止,

解决方法: 将mousemove事件挂在docment,而不是对应的element,此时鼠标滑动只要不出docment范围就不会触发上述情况。

拖动事件完成的动作时是:mousedown(事件的触发) →mousemove(事件的控制) →mouseup(事件的清除) 但是mouseup的时候 同时会触发 点击事件(如果元素上面有点击事件的话)

处理办法:记录mousedown(记录开始时间) →mousemove→mouseup(记录结束时间) 的时间 根据时间长短判断是进行了点击事件还是进行了拖拽事件。

正常需求的话 就希望拖拽元素只在屏幕的可视范围内进行拖拽,不能跑出去。

在onmousemove 中添加边缘控制就好,具体范围可以根据具体需求更改。

<!doctype html>

<html>

<head>

<meta charset="utf-8">

<title>沿正弦曲线移动的圆</title>

<style>

body{

margin:0

padding:0

}

</style>

</head>

<body>

<canvas id="duxing.org"></canvas>

<script src="https://code.createjs.com/createjs-2015.05.21.min.js"></script>

<script>

var canvas = document.getElementById('duxing.org')

function fullScreenCanvas(){

var clientWidth = document.body.clientWidth,

clientHeight = document.body.clientHeight

canvas.setAttribute('width', clientWidth)

canvas.setAttribute('height', clientHeight)

}

var stage = new createjs.Stage(canvas)

var circle = new createjs.Shape()

circle.graphics.beginStroke('#000')

circle.graphics.beginFill('#FFF000')

circle.graphics.drawCircle(0, 0, 30)

circle.x = 0

circle.y = 75

stage.addChild(circle)

var derection = 1

createjs.Ticker.setFPS(24)

createjs.Ticker.addEventListener("tick", function(e){

circle.x += 1 * derection

circle.y = 50 + Math.sin( circle.x / 2 ) * 3

stage.update()

if( circle.x >canvas.width || circle.x <0){

derection *= -1

}

})

</script>

</body>

</html>