5、事件

play 播放事件 可判断歌曲是否正在播放中
pause 暂停事件 判断歌曲是否暂停
loadstart,durationchange,loadeddata,progress,canplay,canplaythrough。(这些事件在加载过程中是按以上顺序触发的)
以上这些事件可以通过事件监听对其做相应处理。

6、案例

HTML5音乐播放器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel="stylesheet" href="http://at.alicdn.com/t/font_1472646293_377639.css">
    <script src="js/jquery.js"></script>
    <style type="text/css">
        body{
            /*background: -webkit-linear-gradient(  ,#5621b8 0%,#781fa3 50%,#bc24b7 90%)*/
            background: -webkit-linear-gradient( right, #bc24b7 30%,#781fa3 50% ,#5621b8 80%)
        }
        p,ul,li{
            list-style: none;
            margin:0;
            padding: 0; 
        }
        #box{
            width: 1000px;
            height: 600px;
            /*border: 1px solid #000;*/
            position: absolute;
            top: 50%;
            left: 50%;
            margin-top: -300px;
            margin-left: -500px;
        }
        .top{
            height: 400px;
        }
        .pic-b{
            float: left;
            position: relative;
            width: 400px;
            height: 400px;
        }
        .picbg{
            
            width: 400px;
            height: 400px;
            background: url(img/cd.png) no-repeat center;
            background-size: 100%;
            border-radius: 50%;
            box-shadow: 1px 1px 15px #000;
            /*animation: active 3s linear infinite  .5s; */
        }
        @-webkit-keyframes active{
            from{
                -webkit-transform:rotate(0deg);
            }
            to{
                -webkit-transform:rotate(360deg);
            }
        }
        .pic{
            width: 200px;
            height: 200px;
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left:-100px;
            margin-top: -100px;
            background: url(img/img.jpg)no-repeat center;
            background-size: 100%;
            border-radius: 50%;
        }
        .cdt{
            position: absolute;
            top: 0;
            right: -20px;
            /*background: url(img/cd_tou.png)no-repeat center;*/
            transform-origin: 60px 12px;
            transform: rotate(-21deg);
            -webkit-transition:all 1s;
        }
        .play{
            margin-top: 100px;
            width: 500px;
            float: right;
            font-family:"微软雅黑";
            color: #fff;
            text-align: center; 
            font-size: 18px;
        }
        /*.play2:visited{
            
        }*/
        .pl-c{
            margin-top: 20px;
            
        }
        .iconfont{
            color: #fff;
            cursor: pointer;
            font-size: 25px;
        }
        .pl-c-l{
            float: left;
            margin-left: 80px;
        }
        .pl-c-r{
            position: relative;    
            float: right;
            margin-right: 80px;
        }
        .pl-b{
            float: left;
        
            margin-left: 50px;

        }
        /*.pl-c-r .icon-1yinpinbofangmin{
            color:#eee;
        }*/
        /*.icon-1yinpinbofangmin:hover .vol{
            display: block;
        }*/
            .vol {
            display: none;
            position: absolute;
            width: 8px;
            height: 100px;
            top: -100px;
            left: 70px;
            background:  #E2D7D7;
            border-radius: 15px;
            border: 3px solid #fff;
        }
        .vol .vol1{
            position: absolute;
            width: 8px;
            height: 50px;
            bottom: 0px;
            left: 0px;
            background:#EF6343;
            border-radius: 4px;
        }
        .jindu{
            vertical-align: top;
            display: inline-block;
            margin-top: 12px;
            margin-left: 16px;
            width: 300px;
            height: 6px;
            border-radius: 1px;
            background: rgba(0,0,0,.4);
            position: relative;
            cursor: pointer;
        }
        .xxx{
            position: absolute;
            top: 0;
            left: 0;
            border-radius: 1px;
            background: #fff;
            height: 6px;
        }

        .center{
            width: 800px;
            margin: 80px auto;
            font-family: "微软雅黑"

        }
        .center li{
            text-align:center; 
            width: 162px;
            /*background:rgba(255,255,255,0.4);*/
            font-size: 27px;
            color: #fff;
            float: left;
            padding: 5px 5px 0 ;
            height: 75px;
            line-height: 40px;
            margin: 0 10px;
            border-radius: 8px;
            /*background: -webkit-linear-gradient(rgba(255,255,255,0.4) 46px,rgba(255,255,255,.1) 46px);*/
            position: relative;
            box-shadow: 2px 2px 4px rgba(0,0,0,.3);
            cursor: pointer;
        }
        .center li:hover{
            /*background: #000;*/
            -webkit-filter: blur(1px);
        }
        .center li:after{
            content: "";
            display: block;
            position: absolute;
            top: 0;
            left: 0;
            background: rgba(255,255,255,.3);
            border-radius: 8px 8px 0 0;
            width:100%;
            height: 50%;
            
        }
        .center li p{
            clear: both;
            font-size: 12px;
            line-height: 20px;
        }
        .center li b{
            font-size: 14px;
            
        }
    </style>
</head>
<body>
    <div id="box">
        <div class="top">
          <div class="pic-b">
            <div class="picbg">
                <div class="pic"></div>
            </div>    
            <img class="cdt" src="img/cd_tou.png" />
        </div>
            <div class="play">
              <div class="pl-t">
                <h1 style="font-size:50px;font-weight:normal">演员</h1>
                <span style="font-size:24px;">薛之谦</span>&nbsp;
                <span>专辑:绅士</span>
              </div>
              <div class="pl-c">
                   <div class="pl-c-l">
                         <span class="iconfont icon-back prev"></span>
                         <span class="iconfont icon-you-copy play2"></span>
                         <span class="iconfont icon-kuai next"></span>
                    </div>
                    <div class="pl-c-r">
                        <span class="iconfont icon-suijibofang"></span>&nbsp;
                        <span class="iconfont icon-zhongxinbofangicon"></span>&nbsp;
                        <span class="iconfont icon-1yinpinbofangmin"></span>
                        <div class="vol">
                            <div class="vol1"></div>
                        </div>
                    </div>
                    
                    <div class="pl-b">
                    <span class="time" style="font-size: 12px;">
                        <n class="min1">00</n>:<n class="sec1">00</n>/<n class="min2">00</n>:<n class="sec2">00</n> 
                    </span>
                        <div class="jindu">
                            <p class="xxx"></p>
                        </div>
                    </div>

              </div>
            </div>
        </div>
        <ul class="center">
            <li>丑八怪<p><b>薛之谦</b><span>专题:绅士</span></p></li>
            <li>绅士<p><b>薛之谦</b><span>专题:绅士</span></p></li>
            <li>一半<p><b>薛之谦</b><span>专题:绅士</span></p></li>
            <li>认真的雪<p><b>薛之谦</b><span>专题:绅士</span></p></li>
        </ul>
    </div>
    <audio src="music/演员 - 薛之谦.mp3" type="audio/mp3" >
     <!--  <source > -->
    </audio>
    <script>
        var audio=document.getElementsByTagName('audio')[0]; 
        var onoff=true;
        //  点击开关
        var onoff1=true; //音量开关
        var jindu;
        var weizhi;
        // var weiMin;
        // var weiSec;
         function changeMusicActive(){
            clearTimeout(t2);
            rotateClear();
            $(".play2").removeClass('icon-you-copy');
            $(".play2").addClass('icon-zantingjian');
            onoff=false;
            //延时播放,以让它有重新播放的特效
            var t2=setTimeout(function(){
            $(".picbg").css('animation', ' active 3s linear infinite  .5s');
            $(".cdt").css('transform', 'rotate(0deg)');
            musicTime();   
            },500)
        }
        function musicStart(){
            audio.load();
            audio.play();
        }
        function musicTime(){     
                var time=null;
                //歌曲时间
                 jindu=audio.duration;
                // var Jin=parseInt(jindu/60)<10 ? "0"+parseInt(jindu/60):parseInt(jindu/60);
                $('n.min2').text(parseInt(jindu/60));
                $('n.sec2').text(parseInt(jindu%60));
                
            }    
        function rotateClear(){
            $(".picbg").css('animation', '');  //清除旋转
            $(".cdt").css('transform', 'rotate(-21deg)');
        }
        var arrmusics=[["music/丑八怪 - 薛之谦.mp3","丑八怪"],["music/绅士 - 薛之谦.mp3","绅士"],["music/一半 - 薛之谦.mp3","一半"],["music/认真的雪 - 薛之谦.mp3","认真的雪"]];
        
        var $index=4;
    $(".center > li").click(function(){
        //先清除状态
        changeMusicActive();

        $index=$(this).index();
        audio.src=arrmusics[$index][0];
        $("h1").text(arrmusics[$index][1]);
        musicStart();
        // musicTime();   //写在这时间读不出来必须延迟等到加载完    
    })
    console.log($index);
    audio.addEventListener('timeupdate',function(){
        weizhi=audio.currentTime;
        var weiMin=parseInt(weizhi/60)<10 ? "0"+parseInt(weizhi/60):parseInt(weizhi/60);
        var  weiSec=parseInt(weizhi%60)<10 ? "0"+parseInt(weizhi%60):parseInt(weizhi%60);
        $('n.min1').text(weiMin);
        $('n.sec1').text(weiSec);
        var percent=audio.currentTime/audio.duration;
        // console.log(percent)
        $(".xxx").css('width', 300*percent);
        if (weizhi>=jindu) {
            rotateClear();
            $index++;
        if ($index>3) $index=0;
        audio.src=arrmusics[$index][0];
        $("h1").text(arrmusics[$index][1]);
        musicStart();
        changeMusicActive();
        }
    })
    //上一首
    
    $(".prev").click(function() {
        $index--;
        if ($index<0) $index=3;
        audio.src=arrmusics[$index][0];
        $("h1").text(arrmusics[$index][1]);
        musicStart();
        changeMusicActive();
    });
    //下一首
    $(".next").click(function() {
        $index++;
        if ($index>3) $index=0;
        audio.src=arrmusics[$index][0];
        $("h1").text(arrmusics[$index][1]);
        musicStart();
        changeMusicActive();
    });
    //随机播放键
    $('.icon-suijibofang').click(function(event) {
        $index=Math.floor(Math.random()*4);
        audio.src=arrmusics[$index][0];
        $("h1").text(arrmusics[$index][1]);
        musicStart();
        changeMusicActive();
    });
    
    //进度移动
    $('.jindu').click(function(ev){
        ev=ev||event;
        var jindu_w=ev.clientX-$(".jindu").offset().left;  //offset如有定位的话返回的值为父级,否则相当于y值
        // console.log(parseInt(jindu_w/300*audio.duration));
        audio.currentTime=parseInt(jindu_w/300*audio.duration);

    })
    $(".play2").click(function() {
        jindu=0;
        weizhi=0;
         musicTime();
        
        if (onoff) {
            audio.play();
            // $(this).attr('class', 'iconfont icon-zantingjian play2');  两种换class名的方法
                $(this).removeClass('icon-you-copy');
                $(this).addClass('icon-zantingjian');
                //添加图画旋转
                $(".picbg").css('animation', ' active 3s linear infinite  .5s');
                $(".cdt").css('transform', 'rotate(0deg)');
        }else{
            audio.pause();
            $(this).removeClass('icon-zantingjian');
            $(this).addClass('icon-you-copy');
            rotateClear();
        }
        onoff=!onoff
    });

    //音量键的设置
    audio.volume=0.5;
    var t=null;
    $(".icon-1yinpinbofangmin").mouseover(function() {
        $(".vol").show();
    }).mouseout(function(event) {
         t=setTimeout(function(){
        $(".vol").hide();
        },1000);
    });
    var volpast;
    $(".icon-1yinpinbofangmin").click(function() {
        
        //音量键点击一下静音
        if (onoff1) {
            volpast= $(".vol1").css('height');
            $(this).attr('class', 'iconfont icon-1');
        audio.volume=0;
        $(".vol1").css('height', 0);
        }else{   //再点击一下开音
            $(this).attr('class', 'iconfont icon-1yinpinbofangmin');
            audio.volume = parseInt(volpast)/100;
            console.log(audio.volume);
            $('.vol1').css('height', volpast);
        }
        onoff1=!onoff1;
    });
        $(".vol").mouseover(function(){    
            clearTimeout(t);
            $(this).show();
        }).mouseout(function(event) {

            $(this).hide();
        });
        //声音大小
        $(".vol").click(function(ev) {
            ev=ev||event;
            var volH=$('.vol').offset().top + 100 - event.clientY
            $(".vol1").css('height', volH);
            audio.volume=volH/100;
        });

        //重播
        $(".icon-zhongxinbofangicon").click(function(){
            musicStart();
        })

    </script>
</body>
</html>

Canvas

0-1 canvas element

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Canvas Element</title>
</head>
<body>
  <canvas id="canvas" width="578" height="200"></canvas>
  <script>
    var canvas = document.getElementById('canvas')
    var context = canvas.getContext('2d')

    context.beginPath()
    context.moveTo(100, 150)
    context.lineTo(450, 50)
    context.stroke()
  </script>
</body>
</html>

1-1 line basic

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Line Basic</title>
</head>
<body>
  <canvas id="canvas" width="578" height="200"></canvas>
  <script>
    var canvas = document.getElementById('canvas')
    var context = canvas.getContext('2d')

    context.beginPath()
    context.moveTo(100, 150)
    context.lineTo(450, 50)

    context.strokeStyle = '#ff0000'
    context.lineWidth = 15
    context.stroke()
  </script>
</body>
</html>

1-2 line cap

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Line cap</title>
</head>
<body>
  <canvas id="canvas" width="578" height="200"></canvas>
  <script>
    var canvas = document.getElementById('canvas')
    var context = canvas.getContext('2d')

    context.beginPath()
    context.moveTo(200, canvas.height / 2 - 50)
    context.lineTo(canvas.width - 200, canvas.height / 2 - 50)
    context.lineWidth = 20;
    context.strokeStyle = '#0000ff'
    context.lineCap = 'butt'
    context.stroke()

    context.beginPath()
    context.moveTo(200, canvas.height / 2)
    context.lineTo(canvas.width - 200, canvas.height / 2)
    context.lineWidth = 20;
    context.strokeStyle = '#0000ff'
    context.lineCap = 'round'
    context.stroke()

    context.beginPath()
    context.moveTo(200, canvas.height / 2  + 50)
    context.lineTo(canvas.width - 200, canvas.height / 2 + 50)
    context.lineWidth = 20;
    context.strokeStyle = '#0000ff'
    context.lineCap = 'square'
    context.stroke()
  </script>
</body>
</html>

2-1 arc

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Arc</title>
</head>
<body>
  <canvas id="canvas" width="578" height="200"></canvas>
  <script>
    var canvas = document.getElementById('canvas')
    var context = canvas.getContext('2d')

    var x = canvas.width / 2
    var y = canvas.height / 2
    var radius = 75
    var startAngle = 1.1 * Math.PI
    var endAngle = 1.9 * Math.PI
    var counterClockwise = false

    context.beginPath()
    context.arc(x, y, radius, startAngle, endAngle, counterClockwise)

    context.strockStyle = 'black'
    context.stroke()
  </script>
</body>
</html>

2-2 quadratic curve

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Quadratic curve</title>
</head>
<body>
  <canvas id="canvas" width="578" height="200"></canvas>
  <script>
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');

    context.beginPath()
    context.moveTo(188, 150)
    context.quadraticCurveTo(188, 0, 488, 150)
    context.lineWidth = 10

    context.strokeStyle = 'black'
    context.stroke()
  </script>
</body>
</html>

2-3 bezier curve

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Bezier curve</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      context.beginPath()
      context.moveTo(188, 130)
      context.bezierCurveTo(140, 10, 288, 10, 388, 170)

      context.lineWidth = 10
      context.strokeStyle = 'black'
      context.stroke()
    </script>
  </script>
</body>
</html>

3-1 path

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Path</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      context.beginPath()
      context.moveTo(100, 20)

      context.lineTo(200, 160)

      context.quadraticCurveTo(230, 200, 250, 120)

      context.bezierCurveTo(290, -40, 300, 200, 400, 150)

      context.lineTo(500, 90)

      context.lineWidth = 5
      context.strokeStyle = 'blue'
      context.stroke()
    </script>
  </script>
</body>
</html>

3-2 path join

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Path join</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      context.lineWidth = 25

      context.beginPath()
      context.moveTo(99, 150)
      context.lineTo(149, 50)
      context.lineTo(199, 150)
      context.lineJoin = 'miter'
      context.stroke()

      context.beginPath()
      context.moveTo(239, 150)
      context.lineTo(289, 50)
      context.lineTo(339, 150)
      context.lineJoin = 'round'
      context.stroke()

      context.beginPath()
      context.moveTo(379, 150)
      context.lineTo(429, 50)
      context.lineTo(479, 150)
      context.lineJoin = 'bevel'
      context.stroke()
    </script>
  </script>
</body>
</html>

3-3 rounded corners

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>rounded corners</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      context.lineWidth = 25

      context.beginPath()
      context.moveTo(99, 150)
      context.lineTo(149, 50)
      context.lineTo(199, 150)
      context.lineJoin = 'miter'
      context.stroke()

      context.beginPath()
      context.moveTo(239, 150)
      context.lineTo(289, 50)
      context.lineTo(339, 150)
      context.lineJoin = 'round'
      context.stroke()

      context.beginPath()
      context.moveTo(379, 150)
      context.lineTo(429, 50)
      context.lineTo(479, 150)
      context.lineJoin = 'bevel'
      context.stroke()
    </script>
  </script>
</body>
</html>

4-1 custom shape

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>custom shape</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      context.beginPath()
      context.moveTo(170, 80)
      context.bezierCurveTo(130, 100, 130, 150, 230, 150)
      context.bezierCurveTo(250, 180, 320, 180, 340, 150)
      context.bezierCurveTo(420, 150, 420, 120, 390, 100)
      context.bezierCurveTo(430, 40, 370, 30, 340, 50)
      context.bezierCurveTo(320, 5, 250, 20, 250, 50)
      context.bezierCurveTo(200, 5, 150, 20, 170, 80)

      context.closePath()
      context.lineWidth = 5
      context.strokeStyle = 'blue'
      context.stroke()
    </script>
  </script>
</body>
</html>

4-2 rectangle

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>rectangle</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      context.beginPath()
      context.rect(188, 50, 200, 100)

      context.fillStyle = 'yellow'
      context.fill()

      context.lineWidth = 7
      context.strokeStyle = 'black'
      context.stroke()
    </script>
  </script>
</body>
</html>

4-3 circle

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>circle</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var centerX = canvas.width / 2
      var centerY = canvas.height / 2
      var radius = 70

      context.beginPath()
      context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false)
      context.fillStyle = 'green'
      context.fill()
      context.lineWidth = 5
      context.strokeStyle = '#003300'
      context.stroke()
    </script>
  </script>
</body>
</html>

4-4 semicircle

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>semicircle</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      context.beginPath()
      context.arc(288, 75, 70, 0, Math.PI, false)
      context.closePath()

      context.lineWidth = 5
      context.fillStyle = 'red'
      context.strokeStyle = '#550000'

      context.fill()
      context.stroke()
    </script>
  </script>
</body>
</html>

5-1 color fill

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>color fill</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      context.beginPath()
      context.moveTo(170, 80)
      context.bezierCurveTo(130, 100, 130, 150, 230, 150)
      context.bezierCurveTo(250, 180, 320, 180, 340, 150)
      context.bezierCurveTo(420, 150, 420, 120, 390, 100)
      context.bezierCurveTo(430, 40, 370, 30, 340, 50)
      context.bezierCurveTo(320, 5, 250, 20, 250, 50)
      context.bezierCurveTo(200, 5, 150, 20, 170, 80)

      context.closePath()
      context.lineWidth = 5
      context.strokeStyle = 'blue'
      context.stroke()
      context.fillStyle = 'red'
      context.fill()
    </script>
  </script>
</body>
</html>

5-2 linear gradient

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>linear gradient</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      context.rect(0, 0, canvas.width, canvas.height)

      var grd = context.createLinearGradient(0, 0, canvas.width, canvas.height)
      grd.addColorStop(0, '#8ED6FF')
      grd.addColorStop(1, '#004CB3')

      context.fillStyle = grd
      context.fill()
    </script>
  </script>
</body>
</html>

5-3 radial gradient

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>radial gradient</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      context.rect(0, 0, canvas.width, canvas.height)

      var grd = context.createRadialGradient(238, 50, 10, 238, 50, 300)
      grd.addColorStop(0, '#8ED6FF')
      grd.addColorStop(1, '#004CB3')
      context.fillStyle = grd
      context.fill()
    </script>
  </script>
</body>
</html>

5-4 pattern

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>pattern</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var imageObj = new Image()
      imageObj.src = './wood-pattern.png'
      imageObj.onload = function() {
        var pattern = context.createPattern(imageObj, 'repeat')

        context.rect(0, 0, canvas.width, canvas.height)
        context.fillStyle = pattern
        context.fill()
      }
    </script>
  </script>
</body>
</html>

6-1 draw image

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>draw image</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="400"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var imageObj = new Image()
      imageObj.src = './darth-vader.jpg'
      imageObj.onload = function() {
        context.drawImage(imageObj, 69, 50)
      }
    </script>
  </script>
</body>
</html>

6-2 image size

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>image size</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="400"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var x = 188
      var y = 30
      var width = 200
      var height = 137

      var imageObj = new Image()
      imageObj.src = './darth-vader.jpg'
      imageObj.onload = function() {
        context.drawImage(imageObj, x, y, width, height)
      }
    </script>
  </script>
</body>
</html>

6-3 image crop

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>image crop</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="400"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var sourceX = 100
      var sourceY = 10
      var sourceWidth = 250
      var sourceHeight = 250

      var destWidth = sourceWidth
      var destHeight = sourceHeight
      var destX = canvas.width / 2 - destWidth / 2
      var destY = canvas.height / 2 - destHeight / 2

      var imageObj = new Image()
      imageObj.src = './darth-vader.jpg'
      imageObj.onload = function() {
        context.drawImage(imageObj, sourceX, sourceY, sourceWidth, sourceHeight, 100, 100, destWidth, destHeight)
      }
    </script>
  </script>
</body>
</html>

6-4 image loader

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>image loader</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="400"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var sources = {
        darthVader: './darth-vader.jpg',
        yoda: './yoda.jpg'
      }

      function loadImages(sources, callback) {
        var images = {}
        var loadedImages = 0
        var numImages = 0

        for(var src in sources) {
          numImages++
        }

        for(var src in sources) {
          images[src] = new Image()
          images[src].onload = function() {
            if(++loadedImages >= numImages) {
              callback(images)
            }
          }
          images[src].src = sources[src]
        }
      }

      loadImages(sources, function(images){
        context.drawImage(images.darthVader, 100, 30, 200, 137)
        context.drawImage(images.yoda, 350, 55, 93, 104)
      })
    </script>
</body>
</html

7-1 text basic

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>text basic</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var text = 'Hello World'

      var x = canvas.width / 2
      var y = canvas.height / 2

      context.font = 'bold 20pt Calibri'
      context.fillStyle = 'blue'

      context.textAlign = 'center' // start end left right
      context.textBaseline = 'middle' //top hanging alphabetic bottom

      var metrics = context.measureText(text)
      var width = metrics.width

      context.fillText('(' + width + 'px wide)', x, y)

      // context.strokeStyle = 'red'
      // context.strokeText('Hello World', 150, 100)
    </script>
</body>
</html>

7-2 text wrap

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>text wrap</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var maxWidth = 400
      var lineHeight = 25
      var x = (canvas.width - maxWidth) / 2
      var y = 60
      var text = 'All the world \'s a stage, and all the men and women merely players. They have their exits and their entrances; And one man in his time plays many parts.'

      context.font = '16pt Calibri'
      context.fillStyle = '#333'

      function wrapText(context, text, x, y, maxWidth, lineHeight) {
        var words = text.split(' ')
        var line = ''

        for(var n = 0; n < words.length; n++) {
          var textLine = line + words[n] + ' '
          var metrics = context.measureText(textLine)
          var textWidth = metrics.width
          if (textWidth > maxWidth && n > 0) {
            context.fillText(line, x, y)
            line = words[n] + ' '
            y += lineHeight
          } else {
            line = textLine
          }
        }

        context.fillText(line, x, y)
      }

      wrapText(context, text, x, y, maxWidth, lineHeight)
    </script>
</body>
</html>

8-1 translate

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>translate</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var rectWidth = 150
      var rectHeight = 75

      context.translate(canvas.width / 2, canvas.height / 2)

      context.fillStyle = 'blue'
      context.fillRect(rectWidth / -2, rectHeight / -2, rectWidth, rectHeight)
    </script>
</body>
</html>

8-2 scale

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>scale</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var rectWidth = 150
      var rectHeight = 75

      context.translate(canvas.width / 2, canvas.height / 2)

      context.scale(2, 2)

      context.fillStyle = 'blue'
      context.fillRect(rectWidth / -2, rectHeight / -2, rectWidth, rectHeight)
    </script>
</body>
</html>

8-3 rotate

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>rotate</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var rectWidth = 150
      var rectHeight = 75

      context.translate(canvas.width / 2, canvas.height / 2)

      context.rotate(Math.PI/4)

      context.fillStyle = 'blue'
      context.fillRect(rectWidth / -2, rectHeight / -2, rectWidth, rectHeight)
    </script>
</body>
</html>

8-4 custom transform

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>custom transform</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var rectWidth = 150
      var rectHeight = 75

      // transform matrix
      // a c e
      // b d f
      // 0 0 1

      // 平移
      // 1 0 x
      // 0 1 y
      // 0 0 1

      // 缩放
      // x 0 0
      // 0 y 0
      // 0 0 1

      // 旋转
      // cos(x) -sin(x) 0
      // sin(x) cos(x)  0
      // 0      0       1

      // 变形
      // 1      tan(y) 0
      // tan(x) 1      0
      // 0      0      1

      var rectWidth = 150
      var rectHeight = 75

      var x = canvas.width / 2
      var y = canvas.height / 2

      context.transform(1, 0, 0, 1, x, y)

      // context.rotate(Math.PI/4)
      context.transform(Math.cos(Math.PI/4), Math.sin(Math.PI/4), -Math.sin(Math.PI/4), Math.cos(Math.PI/4), 0, 0)

      // context.transform(2, 0, 0, 2, 0, 0)

      context.fillStyle = 'blue'
      context.fillRect(rectWidth / -2, rectHeight / -2, rectWidth, rectHeight)
    </script>
</body>
</html>

8-5 mirror

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>mirror</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      context.translate(canvas.width/2, canvas.height/2)

      context.scale(-1, 1)

      context.font = '30pt Calibri'
      context.textAlign = 'center'
      context.fillStyle = 'blue'
      context.fillText('Hello World', 0, 0)
    </script>
</body>
</html>

8-6 reset transform

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>reset transform</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="200"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var rectWith = 150
      var rectHeight = 75

      context.translate(canvas.width / 2, canvas.height / 2)
      context.fillStyle = 'blue'
      context.fillRect(-rectWith /2, rectHeight / -2, rectWith, rectHeight)

      // reset transform
      // 1 0 0
      // 0 1 0
      // 0 0 1
      // context.setTransform(1, 0, 0, 1, 0, 0)
      context.fillStyle = 'red'
      context.fillRect(0, 0, rectWith, rectHeight)
    </script>
</body>
</html>

8-7 state stack

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>state stack</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="400"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var rectWidth = 150
      var rectHeight = 75

      context.save()
      context.translate(canvas.width / 2, canvas.height / 2);

      context.save()
      context.rotate(Math.PI / 4);

      context.save()
      context.scale(2, 2);

      context.fillStyle = 'blue';
      context.fillRect(rectWidth / -2, rectHeight / -2, rectWidth, rectHeight);
      context.restore()

      context.fillStyle = 'red';
      context.fillRect(rectWidth / -2, rectHeight / -2, rectWidth, rectHeight);
      context.restore()

      context.fillStyle = 'yellow';
      context.fillRect(rectWidth / -2, rectHeight / -2, rectWidth, rectHeight);
      context.restore()
      
      context.fillStyle = 'green';
      context.fillRect(rectWidth / -2, rectHeight / -2, rectWidth, rectHeight);

    </script>
</body>
</html>

8-8 oval

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>oval</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="400"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var centerX = 0
      var centerY = 0
      var radius = 50

      context.save()
      context.translate(canvas.width/2, canvas.height/2)

      context.scale(2, 1)

      context.beginPath()
      context.arc(centerX, centerY, radius, 0, 2*Math.PI, false)

      context.restore()

      context.fillStyle = '#8ED6FF'
      context.fill()
      context.lineWidth = 5
      context.strokeStyle = 'black'
      context.stroke()

    </script>
</body>
</html>

9-1 shadow

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>shadow</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="400"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      context.rect(188, 40, 200, 100)
      context.fillStyle = 'red'
      context.shadowColor = '#999'
      context.shadowBlur = 20
      context.shadowOffsetX = 15
      context.shadowOffsetY = 15
      context.fill()

    </script>
</body>
</html>

9-2 global alpha

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>global alpha</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="400"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      context.globalAlpha = 0.1
      context.beginPath()
      context.rect(200, 20, 100, 100)
      context.fillStyle = 'blue'
      context.fill()

      context.globalAlpha = 0.5
      context.beginPath()
      context.arc(320, 120, 60, 0, 2 * Math.PI, false)
      context.fillStyle = 'red'
      context.fill()

    </script>
</body>
</html>

9-3 clipping region

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>clipping region</title>
</head>
<body>
    <canvas id="myCanvas" width="578" height="400"></canvas>
    <script>
      var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      var x = canvas.width / 2
      var y = canvas.height / 2
      var radius = 75
      var offset = 50

      context.save();
      context.beginPath()
      context.arc(x, y, radius, 0, 2 * Math.PI, false)
      context.clip()

      context.beginPath()
      context.arc(x - offset, y - offset, radius, 0, 2 * Math.PI, false)
      context.fillStyle = 'blue'
      context.fill()

      context.beginPath()
      context.arc(x + offset, y, radius, 0, 2 * Math.PI, false)
      context.fillStyle = 'yellow'
      context.fill()

      context.beginPath()
      context.arc(x, y + offset, radius, 0, 2 * Math.PI, false)
      context.fillStyle = 'red'
      context.fill()

      context.restore()
      context.beginPath()
      context.arc(x, y, radius, 0, 2 * Math.PI, false)
      context.lineWidth = 10
      context.strokeStyle = 'purple'
      context.stroke()

    </script>
</body>
</html>

9-4 operations

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>operations</title>
</head>
<body>
  <canvas id="myCanvas" width="578" height="430"></canvas>
  <canvas id="tempCanvas" width="578" height="430" style="display:none"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
    var tempCanvas = document.getElementById('tempCanvas')
    var tempContext = tempCanvas.getContext('2d')

    var squareWidth = 55
    var circleRadius = 35
    var shapeOffset = 50
    var operationOffset = 150
    var arr = []

    arr.push('source-atop')
    arr.push('source-in')
    arr.push('source-out')
    arr.push('source-over')
    arr.push('destination-atop')
    arr.push('destination-in')
    arr.push('destination-out')
    arr.push('destination-over')
    arr.push('lighter')
    arr.push('darker')
    arr.push('xor')
    arr.push('copy')

    context.translate(10, 10)
    for (var n = 0; n < arr.length; n++) {
      var thisOperation = arr[n]

      tempContext.save()
      tempContext.clearRect(0, 0, canvas.width, canvas.height)

      tempContext.beginPath()
      tempContext.rect(0, 0, squareWidth, squareWidth)
      tempContext.fillStyle = 'blue'
      tempContext.fill()

      tempContext.globalCompositeOperation = thisOperation

      tempContext.beginPath()
      tempContext.arc(shapeOffset, shapeOffset, circleRadius, 0, 2 * Math.PI, false)
      tempContext.fillStyle = 'red'
      tempContext.fill()
      tempContext.restore()

      tempContext.font = '10pt Verdana'
      tempContext.fillStyle = 'black'
      tempContext.fillText(thisOperation, 0, squareWidth + 45)

      if (n > 0) {
        if (n % 4 === 0) {
          context.translate(operationOffset * -3, operationOffset)
        } else {
          context.translate(operationOffset, 0)
        }
      }

      context.drawImage(tempCanvas, 0, 0)
    }
  </script>
</body>
</html>

10-1 image data

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>image data</title>
</head>
<body>
  <canvas id="myCanvas" width="578" height="430"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');
    var imageObj = new Image()
    imageObj.onload = function () {
      drawImage(this)
    }
    imageObj.src = './darth-vader.jpg'

    function drawImage(imageObj) {
      var imageX = 69
      var imageY = 50
      var imageWidth = imageObj.width
      var imageHeight = imageObj.height
      context.drawImage(imageObj, imageX, imageY)

      var imageData = context.getImageData(imageX, imageY, imageWidth, imageHeight)
      var data = imageData.data

      for (var i = 0; i < data.length; i++) {
        var red = data[i]
        var green = data[i + 1]
        var blue = data[i + 2]
        var alpha = data[i + 3]
      }
    }
  </script>
</body>
</html>

10-2 invert colors

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>invert colors</title>
</head>
<body>
  <canvas id="myCanvas" width="578" height="430"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    var imageObj = new Image()
    imageObj.onload = function () {
      drawImage(this)
    }
    imageObj.src = './darth-vader.jpg'

    function drawImage(imageObj) {
      var x = 69
      var y = 50

      context.drawImage(imageObj, x, y)

      var imageData = context.getImageData(x, y, imageObj.width, imageObj.height)
      var data = imageData.data

      for (var i = 0; i < data.length; i += 4) {
        data[i] = 255 - data[i]
        data[i + 1] = 255 - data[i + 1]
        data[i + 2] = 255 - data[i + 2]
      }

      context.putImageData(imageData, x, y)
    }
  </script>
</body>
</html>

10-3 grayscale

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>grayscale</title>
</head>
<body>
  <canvas id="myCanvas" width="578" height="430"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    var imageObj = new Image()
    imageObj.onload = function () {
      drawImage(this)
    }
    imageObj.src = './darth-vader.jpg'

    function drawImage(imageObj) {
      var x = 69
      var y = 50

      context.drawImage(imageObj, x, y)

      var imageData = context.getImageData(x, y, imageObj.width, imageObj.height)
      var data = imageData.data

      for (var i = 0; i < data.length; i += 4) {
        var brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2]
        data[i] = brightness
        data[i + 1] = brightness
        data[i + 2] = brightness
      }

      context.putImageData(imageData, x, y)
    }
  </script>
</body>
</html>

10-4 get data url

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>get data url</title>
</head>
<body>
  <canvas id="myCanvas" width="578" height="430"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    context.beginPath()
    context.moveTo(170, 80)
    context.bezierCurveTo(130, 100, 130, 150, 230, 150)
    context.bezierCurveTo(250, 180, 320, 180, 340, 150)
    context.bezierCurveTo(420, 150, 420, 120, 390, 100)
    context.bezierCurveTo(430, 40, 370, 30, 340, 50)
    context.bezierCurveTo(320, 5, 250, 20, 250, 50)
    context.bezierCurveTo(200, 5, 150, 20, 170, 80)

    context.closePath()
    context.lineWidth = 10
    context.strokeStyle = '#0000ff'
    context.stroke()
    context.fillStyle = '#8ED6FF'
    context.fill()

    var dataURL = canvas.toDataURL()
    console.log(dataURL)
  </script>
</body>
</html>

10-5 load data url

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>load data url</title>
</head>
<body>
  <canvas id="myCanvas" width="578" height="430"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    var request = new XMLHttpRequest()
    request.open('GET', './dataURL.txt', true)
    request.onreadystatechange = function () {
      if (request.readyState == 4) {
        if (request.status == 200) {
          loadCanvas(request.responseText)
        }
      }
    }
    request.send(null)

    function loadCanvas(dataURL) {
      var imageObj = new Image()
      imageObj.onload = function () {
        context.drawImage(this, 0, 0)
      }
      imageObj.src = dataURL
    }
  </script>
</body>
</html>

10-6 save drawing

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>save drawing</title>
</head>
<body>
  <canvas id="myCanvas" width="578" height="430" style="display:none"></canvas>
  <img src="" id="canvasImg" alt="">
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    context.beginPath()
    context.moveTo(170, 80)
    context.bezierCurveTo(130, 100, 130, 150, 230, 150)
    context.bezierCurveTo(250, 180, 320, 180, 340, 150)
    context.bezierCurveTo(420, 150, 420, 120, 390, 100)
    context.bezierCurveTo(430, 40, 370, 30, 340, 50)
    context.bezierCurveTo(320, 5, 250, 20, 250, 50)
    context.bezierCurveTo(200, 5, 150, 20, 170, 80)

    context.closePath()
    context.lineWidth = 10
    context.strokeStyle = '#0000ff'
    context.stroke()
    context.fillStyle = '#8ED6FF'
    context.fill()

    var dataURL = canvas.toDataURL()
    document.getElementById('canvasImg').src = dataURL
  </script>
</body>
</html>

11-1 clear canvas

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>clear canvas</title>
  <style media="screen">
    body {
      margin: 0;
      padding: 0;
    }
    #buttons {
      position: absolute;
      top: 5px;
      left: 10px;
    }
    #buttons > input {
      padding: 10px;
      display: block;
      margin-top: 5px;
    }
  </style>
</head>
<body>
  <canvas id="myCanvas" width="578" height="430"></canvas>
  <div id="buttons">
    <input type="button" id="clear" name="" value="Clear">
  </div>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    context.beginPath()
    context.moveTo(170, 80)
    context.bezierCurveTo(130, 100, 130, 150, 230, 150)
    context.bezierCurveTo(250, 180, 320, 180, 340, 150)
    context.bezierCurveTo(420, 150, 420, 120, 390, 100)
    context.bezierCurveTo(430, 40, 370, 30, 340, 50)
    context.bezierCurveTo(320, 5, 250, 20, 250, 50)
    context.bezierCurveTo(200, 5, 150, 20, 170, 80)

    context.closePath()
    context.lineWidth = 10
    context.strokeStyle = '#0000ff'
    context.stroke()
    context.fillStyle = '#8ED6FF'
    context.fill()

    document.getElementById('clear').addEventListener('click', function () {
      context.clearRect(0, 0, canvas.width, canvas.height)
    })
  </script>
</body>
</html>

11-2 animation clears

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>animation clears</title>
  <style media="screen">
    body {
      margin: 0;
      padding: 0;
    }
  </style>
</head>
<body>
  <canvas id="myCanvas" width="578" height="430"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    window.requestAnimFrame = (function (callback) {
      return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {
        window.setTimeout(callback, 1000 / 60)
      }
    })()

    function drawRectangle(myRectangle, context) {
      context.beginPath()
      context.rect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height)
      context.fillStyle = '#8ED6FF'
      context.fill()
      context.lineWidth = myRectangle.borderWidth
      context.strokeStyle = 'black'
      context.stroke()
    }

    function animate(myRectangle, canvas, context, startTime) {
      var time = (new Date()).getTime() - startTime
      var linearSpeed = 100
      var newX = linearSpeed * time / 1000
      if (newX < canvas.width - myRectangle.width - myRectangle.borderWidth / 2) {
        myRectangle.x = newX
      }
      context.clearRect(0, 0, canvas.width, canvas.height)

      drawRectangle(myRectangle, context)

      requestAnimFrame(function () {
        animate(myRectangle, canvas, context, startTime)
      })
    }

    var myRectangle = {
      x: 0,
      y: 75,
      height: 50,
      width: 100,
      borderWidth: 5
    }

    drawRectangle(myRectangle, context)

    setTimeout(function () {
      var startTime = (new Date()).getTime()
      animate(myRectangle, canvas, context, startTime)
    }, 1000)
  </script>
</body>
</html>

11-3 acceleration

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>acceleration</title>
  <style media="screen">
    body {
      margin: 0;
      padding: 0;
    }
  </style>
</head>
<body>
  <canvas id="myCanvas" width="578" height="430"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    window.requestAnimFrame = (function (callback) {
      return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {
        window.setTimeout(callback, 1000 / 60)
      }
    })()

    function drawRectangle(myRectangle, context) {
      context.beginPath()
      context.rect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height)
      context.fillStyle = '#8ED6FF'
      context.fill()
      context.lineWidth = myRectangle.borderWidth
      context.strokeStyle = 'black'
      context.stroke()
    }

    function animate(myRectangle, canvas, context, startTime) {
      var time = (new Date()).getTime() - startTime

      var gravity = 200

      myRectangle.y = 0.5 * gravity * Math.pow(time / 1000, 2)

      if (myRectangle.y > canvas.height - myRectangle.height - myRectangle.borderWidth / 2) {
        myRectangle.y = canvas.height - myRectangle.height - myRectangle.borderWidth / 2
      }
      lastTime = time

      context.clearRect(0, 0, canvas.width, canvas.height)

      drawRectangle(myRectangle, context)

      requestAnimFrame(function () {
        animate(myRectangle, canvas, context, startTime)
      })
    }

    var myRectangle = {
      x: 0,
      y: 75,
      height: 50,
      width: 100,
      borderWidth: 5
    }

    drawRectangle(myRectangle, context)

    setTimeout(function () {
      var startTime = (new Date()).getTime()
      animate(myRectangle, canvas, context, startTime)
    }, 1000)
  </script>
</body>
</html>

11-4 oscillation

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>oscillation</title>
  <style media="screen">
    body {
      margin: 0;
      padding: 0;
    }
  </style>
</head>
<body>
  <canvas id="myCanvas" width="578" height="430"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    window.requestAnimFrame = (function (callback) {
      return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {
        window.setTimeout(callback, 1000 / 60)
      }
    })()

    function drawRectangle(myRectangle, context) {
      context.beginPath()
      context.rect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height)
      context.fillStyle = '#8ED6FF'
      context.fill()
      context.lineWidth = myRectangle.borderWidth
      context.strokeStyle = 'black'
      context.stroke()
    }

    function animate(myRectangle, canvas, context, startTime) {
      var time = (new Date()).getTime() - startTime

      var amplitude = 150
      var period = 2000
      var centerx = canvas.width / 2 - myRectangle.width / 2
      var nextX = amplitude * Math.sin(time * 2 * Math.PI / period) + centerx
      myRectangle.x = nextX

      context.clearRect(0, 0, canvas.width, canvas.height)

      drawRectangle(myRectangle, context)

      requestAnimFrame(function () {
        animate(myRectangle, canvas, context, startTime)
      })
    }

    var myRectangle = {
      x: 0,
      y: 75,
      height: 50,
      width: 100,
      borderWidth: 5
    }

    drawRectangle(myRectangle, context)

    setTimeout(function () {
      var startTime = (new Date()).getTime()
      animate(myRectangle, canvas, context, startTime)
    }, 1000)
  </script>
</body>
</html>

11-5 start and stop

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>start and stop</title>
  <style media="screen">
    body {
      margin: 0;
      padding: 0;
    }
  </style>
</head>
<body>
  <canvas id="myCanvas" width="578" height="430"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    window.requestAnimFrame = (function (callback) {
      return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) {
        window.setTimeout(callback, 1000 / 60)
      }
    })()

    function drawRectangle(myRectangle, context) {
      context.beginPath()
      context.rect(myRectangle.x, myRectangle.y, myRectangle.width, myRectangle.height)
      context.fillStyle = '#8ED6FF'
      context.fill()
      context.lineWidth = myRectangle.borderWidth
      context.strokeStyle = 'black'
      context.stroke()
    }

    function animate(myRectangle, canvas, context, startTime, runAnimation) {
      if (runAnimation.value) {
        var time = (new Date()).getTime() - startTime

        var amplitude = 150
        var period = 2000
        var centerx = canvas.width / 2 - myRectangle.width / 2
        var nextX = amplitude * Math.sin(time * 2 * Math.PI / period) + centerx
        myRectangle.x = nextX

        context.clearRect(0, 0, canvas.width, canvas.height)

        drawRectangle(myRectangle, context)

        requestAnimFrame(function () {
          animate(myRectangle, canvas, context, startTime, runAnimation)
        })
      }
    }

    var myRectangle = {
      x: 0,
      y: 75,
      height: 50,
      width: 100,
      borderWidth: 5
    }

    var runAnimation = {
      value: false
    }

    document.getElementById('myCanvas').addEventListener('click', function () {
      runAnimation.value = !runAnimation.value
      if (runAnimation.value) {
        var startTime = (new Date()).getTime()
        animate(myRectangle, canvas, context, startTime, runAnimation)
      }
    })

    drawRectangle(myRectangle, context)
  </script>
</body>
</html>

12-1 mouse coordinates

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>mouse coordinates</title>
  <style media="screen">
    body {
      margin: 0;
      padding: 0;
    }
  </style>
</head>
<body>
  <canvas id="myCanvas" width="578" height="430"></canvas>
  <script>
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    function getMousePos(canvas, evt) {
      var rect = canvas.getBoundingClientRect()
      return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
      }
    }

    function writeMessage(canvas, message) {
      context.clearRect(0, 0, canvas.width, canvas.height)
      context.font = '18pt Calibri'
      context.fillStyle = 'black'
      context.fillText(message, 10, 25)
    }

    canvas.addEventListener('mousemove', function (evt) {
      var mousePos = getMousePos(canvas, evt)
      var message = 'Mouse position:' + mousePos.x + ',' + mousePos.y
      writeMessage(canvas, message)
    }, false)
  </script>
</body>
</html>
Last modification:May 30th, 2020 at 04:13 pm
如果和我讨论问题,请加好友qq/wx