12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- <template>
- <div class="compass-container">
- <div class="compass" :style="compassStyle">
- <div class="arrow"></div>
- </div>
- <p>当前方向: {{ direction }}°</p>
- </div>
- </template>
- <script>
- export default {
- data() {
- return {
- direction: 0, // 当前方向
- compassStyle: {
- transform: `rotate(${this.direction}deg)` // 初始化旋转角度
- }
- };
- },
- mounted() {
- // 浏览器支持的设备方向API
- if (window.DeviceOrientationEvent) {
- window.addEventListener("deviceorientation", this.handleOrientation);
- } else {
- alert("您的设备不支持设备方向API");
- }
- },
- beforeDestroy() {
- // 清理事件监听器
- if (window.DeviceOrientationEvent) {
- window.removeEventListener("deviceorientation", this.handleOrientation);
- }
- },
- methods: {
- handleOrientation(event) {
- // 获取 alpha (旋转角度)
- let alpha = event.alpha; // 设备的旋转角度
- if (alpha !== null) {
- this.direction = alpha;
- this.compassStyle.transform = `rotate(${this.direction}deg)`; // 更新旋转角度
- }
- }
- }
- };
- </script>
- <style scoped>
- .compass-container {
- text-align: center;
- padding: 20px;
- }
- .compass {
- width: 200px;
- height: 200px;
- border: 10px solid #444;
- border-radius: 50%;
- margin: 0 auto;
- position: relative;
- background-color: #f0f0f0;
- display: flex;
- justify-content: center;
- align-items: center;
- }
- .arrow {
- width: 5px;
- height: 50px;
- background-color: red;
- position: absolute;
- top: 25%;
- }
- </style>
|