HTML5 指南针

简爱代码>JavaScript2014-12-7 12:2151183
HTML5 新的 API 获取手机 传感器,实现指南针功能的代码
代码并不复杂,主要是 找指南针的 图片比较费时 [衰/]

DEMO 页面

具体效果
截图为 米2s 下的 UC 浏览器
指南针.png

包括全套的
HTML CSS JS

具体代码如下:
<meta charset="utf-8" />

<!-- CSS 样式 -->
<style>
body {
  width: 90%;
}
.ja-center {
  width: 100%;
  font-size: 24px;
  text-align: center;
}
.compass {
  position: relative;
  width: 300px;
  height: 300px;
  padding: 0;
  margin: 0 auto;
}
.compass .compass_bg {
  position: absolute;
  width: 300px;
  height: 300px;
  background: url(/content/uploadfile/201412/0d231417895085.png) center no-repeat;
}
.compass .compass_pointer {
  position: absolute;
  width: 200px;
  height: 200px;
  background: url(/content/uploadfile/201412/246e1417895084.png) center no-repeat;
  margin: 50px;
}
</style>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<script src="http://api.asilu.com/cdn/jquery.js"></script>
<div class="ja-center">指南针</div>

<!-- 指南针 HTML -->
<div class="compass">
  <div class="compass_bg"></div>
  <div class="compass_pointer"></div>
</div>

<div class="tips ja-center"></div>
<div class="ss"></div>

<!-- JS 代码 -->
<script>
var $tips = $('.tips'),
  $compass_pointer = $('.compass_pointer'),
  DIRECTION, COMPASS_ZH;

// 方向传感器
if ("ondeviceorientation" in window) {
  window.addEventListener(
    "deviceorientation",
    function(e){
      DIRECTION = e.alpha // 磁场方向
    },
    false
  );
  compass();
} else {
  $tips.html('不支持 指南针');
  $('.compass').css({width:0, height:0}).html('');
}

function compass(){
  $compass_pointer.css('transform', 'rotate('+ Math.round(DIRECTION) +'deg)');
  setTimeout(compass, 200);

  // 以下代码只为了显示 方向 可以忽略
  s = DIRECTION
  if(s < 22.5)       COMPASS_ZH = '北'
  else if(s < 67.5)  COMPASS_ZH = '西北'
  else if(s < 112.5) COMPASS_ZH = '西'
  else if(s < 157.5) COMPASS_ZH = '西南'
  else if(s < 202.5) COMPASS_ZH = '南'
  else if(s < 247.5) COMPASS_ZH = '东南'
  else if(s < 292.5) COMPASS_ZH = '东'
  else if(s < 337.5) COMPASS_ZH = '东北'
  else COMPASS_ZH = '北'
  $tips.html(COMPASS_ZH +'<br>'+Math.round(DIRECTION)+'&#176;');
}
</script>



本文出自简爱博客,转载时请注明出处及相应链接。

评论

  1. powertony2014-12-25 00:52回复

    如果可以用的話那就太利害的主意

    1. 简爱2014-12-25 01:18回复

      @powertony:确认手机 有这个传感器就 OK 了,大多 浏览器都支持

  2. mrxn2014-12-08 12:20回复

    [哈哈/] 我是凑热闹的

发表评论

电子邮件地址不会被公开。必填项已用*标注