1. 程式人生 > >js 手機搖一搖

js 手機搖一搖

開發十年,就只剩下這套架構體系了! >>>   

const shark = (fn) => {
	const shake = 3000;
	let last_update = 0;
	let x = 0;
	let y = 0;
	let z = 0;
	let last_x = 0;
	let last_y = 0;
	let last_z = 0;
	const deviceMotionHandler = (eventData) => {
		const acceleration = eventData.accelerationIncludingGravity;
		const currTime = new Date().valueOf();
		const diffTime = currTime - last_update;
		if (diffTime > 100) {
			last_update = currTime;
			x = acceleration.x;
			y = acceleration.y;
			z = acceleration.z;
			const speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 20000
			if (speed > shake) {
				fn()
			}
			last_x = x;
			last_y = y;
			last_z = z;
		}
	}

	if (window.DeviceMotionEvent) {
		window.addEventListener('devicemotion', deviceMotionHandler, false);
	} else {
		alert('本裝置不支援devicemotion事件');
	}
}


export {
	shark
}