最近在用Vue开发一款Webapp项目,在研究长按响应的时候,看到原生安卓程序在按压时,会有一个按压反馈,打开知乎随便点击一条信息就可以看到效果,从按压为原点,向外扩散出阴影区域表示你点击到了,这是一个非常好的效果,及时的给用户触感反馈,现在我们使用原生js实现。
代码如下:
var containers = ''
var canvas = {}
var centerX = 0
var centerY = 0
var color = ''
var context = {}
var element = {}
var radius = 0
var requestAnimFrame = (function () {
return (
window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callBack) {
window.setTimeout(callBack, 1000 / 60)
}
)
}(this))
var draw = function () {
context.beginPath()
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false)
context.fillStyle = color
context.fill()
radius += 2
if (radius < element.offsetWidth) {
requestAnimFrame(draw)
}
}
var getElementPosition = function (e) {
var x = 0; var y = 0
while (e != null) {
x += e.offsetLeft
y += e.offsetTop
e = e.offsetParent
}
return { x: x, y: y }
}
var press = function () {
// 如果这个元素的位置内只有一个手指的话
if (event.targetTouches.length === 1) {
console.log('当前只有一个触点')
}
// event.toElement.parentElement.dataset.color
color = event.srcElement.parentElement.dataset.color
element = event.srcElement
context = element.getContext('2d')
radius = 0
centerX = Math.abs(event.touches[0].pageX - getElementPosition(element).x)
centerY = Math.abs(event.touches[0].pageY - getElementPosition(element).y)
context.clearRect(0, 0, element.width, element.height)
draw()
}
var init = function () {
containers = document.getElementsByClassName('material-design')
containers = Array.prototype.slice.call(containers)
for (var i = 0; i < containers.length; i += 1) {
canvas = document.createElement('canvas')
canvas.addEventListener('touchstart', press, false)
containers[i].appendChild(canvas)
canvas.style.width = '100%'
canvas.style.height = '100%'
canvas.width = canvas.offsetWidth
canvas.height = canvas.offsetHeight
}
}
export default function setWater () {
init()
}
网友评论