[html5怎么载入图片]html5图片随手机重力感应而移动效果制作教程

更新时间:2021-02-28    来源:php函数    手机版     字体:

【www.bbyears.com--php函数】

实现方法一:重力感应

 html和css如下:

1.jpg

 加载函数如下:

 代码如下function readyFn() {
'use strict'
var dom = document.querySelector('.big-bg'),
img = dom.querySelector('img');
var IMG_W = img.width,
IMG_H = img.height;
var WIN_W = document.documentElement.clientWidth,
WIN_H = document.documentElement.clientHeight;
var timefragment = 0,               // 时间片计时
nowts = 0;                      // 当前时间
// 设置默认的left/top
dom.style.top = -(IMG_H - WIN_H) / 2 + 'px'
dom.style.left = -(IMG_W - WIN_W) / 2 + 'px'
window.addEventListener('deviceorientation', function (evt) {
nowts = new Date().getTime();
// 控制时间片
if (nowts  - timefragment > 37) {
timefragment = nowts;
var alpha = evt.alpha,          //垂直于屏幕的轴 0 ~ 360
beta = evt.beta,            //横向 X 轴 -180 ~ 180
gamma = evt.gamma;          //纵向 Y 轴 -90 ~ 90
var top = parseInt(dom.style.top, 10) || 0,
left = parseInt(dom.style.left, 10) || 0;
var _top, _left;
_top = top + (beta / 180 * 30);
_left = left + (gamma / 90 * 30);
_top = _top >= 0 ? 0 : (_top < (WIN_H - IMG_H) ? (WIN_H - IMG_H) : _top);
_left = _left >= 0 ? 0 : (_left < (WIN_W - IMG_W) ? (WIN_W - IMG_W) : _left);
dom.style.top = _top + 'px'
dom.style.left = _left + 'px'
}
}, false);
}

实现方法二:parallax插件模拟

parallax这个插件,可以模拟设备感应,手势感应!

html代码如下:

1.jpg

    可以通过data-depth 设置感应的深度!

    可以通过js方式书写:

 代码如下var scene = document.getElementById('scene');
var parallax = new Parallax(scene);

    也可以通过jquery方式书写:

 代码如下 $('#scene').parallax();

本文来源:http://www.bbyears.com/jiaocheng/117690.html