日期:2014-05-17  浏览次数:20700 次

HTML5 API简介一(Canvas,Audio/Video,Geolocation)

?

本文来自:http://www.myext.cn/webkf/18457.html

1.Canvas?
顾名思义,画布,你在上面画画

<!DOCTYPE html>
<html>
  <canvas id="canvas" style="border: 1px solid;"  width="250" height="250"> </canvas>
  <script>
	function drawTriangle(context){//画三角形
	    context.beginPath();
	    context.moveTo(0, 0);
	    context.lineTo(30, -30);
	    context.lineTo(60, 0);
	    context.lineTo(0, 0);
	    context.fillStyle = '#339900';
	    context.fill();
	    context.closePath();
	}
	function draw() {
	    var canvas = document.getElementById('canvas');//获取画布
	    var context = canvas.getContext('2d');//获取画笔

	    context.save();

	    context.translate(30, 60);//移动基准位置
	    drawTriangle(context);//画第一个三角形
	    context.stroke();

	    context.translate(60, 90);//移动基准位置
	    drawTriangle(context);//画第二个三角形
	    context.stroke();

	    context.restore();
	}
	window.addEventListener("load", draw, true);
  </script>
</html>
在浏览器里的样子?
?

2.Audio/Video?
无需插件,播放音频,视频,每个浏览器能支持的格式不一样,自己掂量吧?
!DOCTYPE html>
<html>
  <audio controls>
    <source src="johann_sebastian_bach_air.ogg">
    <source src="johann_sebastian_bach_air.mp3">
    An audio clip from Johann Sebastian Bach.
  </audio>
</html>
Chrome中Audio的样子?
?
如何在JS中控制Audio的播放?
<!DOCTYPE html>
<html>
  <audio id="clickSound">
    <source src="johann_sebastian_bach_air.ogg">
    <source src="johann_sebastian_bach_air.mp3">
  </audio>

  <button id="toggle" onclick="toggleSound()">Play</button>

  <script type="text/javascript">
    function toggleSound() {
        var music = document.getElementById("clickSound");
        var toggle = document.getElementById("toggle");
        if (music.paused) {
          music.play();
          toggle.innerHTML = "Pause";
        }
        else {
          music.pause();
          toggle.innerHTML ="Play";
        }
    }
  </script>
</html>
Video播放和控制?
<!DOCTYPE html>
<html>
  <video id="movies" controls onmouseover="this.play()" onmouseout="this.pause()" autobuffer="true"
    width="400px" height="300px">
    <source src="Intermission-Walk-in.ogv" type='video/ogg; codecs="theora, vorbis"'>
    <source src="Intermission-Walk-in_512kb.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
  </video>
</html>
Chrome中Video的样子?
?

3.Geolocation?
获取用户地理位置,用户可以选择是否愿意,目前来说相当的不靠谱,fanqiang后可以在Firefox测试成功,因为Firefox使用的Google的地理服务,看看代码,也比较简单?
<script type="text/javascript">
    function loadDemo() {
        if(navigato