-
Notifications
You must be signed in to change notification settings - Fork 32
/
3dtouch.js
72 lines (61 loc) · 2.06 KB
/
3dtouch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
var element = document.getElementById('forceMe');
var forceValueOutput = document.getElementById('forceValue');
var background = document.getElementById('background');
var touch = null;
function onTouchStart(e) {
e.preventDefault();
checkForce(e);
}
function onTouchMove(e) {
e.preventDefault();
checkForce(e);
}
function onTouchEnd(e) {
e.preventDefault();
setTimeout(renderElement.bind(null, 0), 10);
touch = null;
}
// use timeout-based method only on devices not supporting ontouchforcechange
function checkForce(e) {
if('ontouchforcechange' in document === false) {
touch = e.touches[0];
setTimeout(refreshForceValue.bind(touch), 10);
}
}
// the maximum force value of a touch event is 1
function onTouchForceChange(e) {
renderElement(e.changedTouches[0].force);
}
// the maximum force value of a click event is 3
function onClickForceChange(e) {
renderElement(e.webkitForce / 3);
}
// iOS versions lower than iOS 10 do not support the touchforcechange event, so refresh manually
function refreshForceValue() {
var touchEvent = this;
var forceValue = 0;
if(touchEvent) {
forceValue = touchEvent.force || 0;
setTimeout(refreshForceValue.bind(touch), 10);
}else{
forceValue = 0;
}
renderElement(forceValue);
}
// update the element according to the force value (between 0 and 1)
function renderElement(forceValue) {
window.requestAnimationFrame(function() {
element.style.webkitTransform = 'translateX(-50%) translateY(-50%) scale(' + (1 + forceValue * 1.5) + ')';
background.style.webkitFilter = 'blur(' + forceValue * 30 + 'px)';
forceValueOutput.innerHTML = 'Force: ' + forceValue.toFixed(4);
});
}
// add event listeners
function addForceTouchToElement(elem) {
elem.addEventListener('touchstart', onTouchStart, false);
elem.addEventListener('touchmove', onTouchMove, false);
elem.addEventListener('touchend', onTouchEnd, false);
elem.addEventListener('webkitmouseforcechanged', onClickForceChange, false);
elem.addEventListener('touchforcechange', onTouchForceChange, false);
}
addForceTouchToElement(element);