zoukankan      html  css  js  c++  java
  • js封装、简单实例源码记录

    1、运动封装:doMove ( obj, attr, dir, target, endFn )  加入回调、&&、||用法注释

    <script>
    var oBtn1 = document.getElementById('btn1');
    var oDiv = document.getElementById('div1');
    
    oBtn1.onclick = function () {
        
        // doMove ( oDiv, 'width', 34, 600 );
        doMove ( oDiv, 'left', 12, 900, function () {
            doMove ( oDiv, 'top', 34, 500 );
        });
    
    };
    
    function doMove ( obj, attr, dir, target, endFn ) {
        
        dir = parseInt(getStyle( obj, attr )) < target ? dir : -dir;
        
        clearInterval( obj.timer );
        
        obj.timer = setInterval(function () {
            
            var speed = parseInt(getStyle( obj, attr )) + dir;            // 步长
            
            if ( speed > target && dir > 0 ||  speed < target && dir < 0  ) {
                speed = target;
            }
            
            obj.style[attr] = speed + 'px';
            
            if ( speed == target ) {
                clearInterval( obj.timer );
                
                /*
                if ( endFn ) {
                    endFn();
                }
                */
                endFn && endFn();  //只有endFn条件为真就会执行endFn()
                //alert(getStyle(obj, 'left')||3);     //哪边为true就返回哪边  布尔、string、number、object、function
            }
            
        }, 30);
    }
    
    function getStyle ( obj, attr ) { return obj.currentStyle?obj.currentStyle[attr] : getComputedStyle( obj )[attr]; }
    </script><script>
    var oBtn1 = document.getElementById('btn1');
    var oDiv = document.getElementById('div1');
    
    oBtn1.onclick = function () {
        
        // doMove ( oDiv, 'width', 34, 600 );
        doMove ( oDiv, 'left', 12, 900, function () {
            doMove ( oDiv, 'top', 34, 500 );
        });
    
    };
    
    function doMove ( obj, attr, dir, target, endFn ) {
        
        dir = parseInt(getStyle( obj, attr )) < target ? dir : -dir;
        
        clearInterval( obj.timer );
        
        obj.timer = setInterval(function () {
            
            var speed = parseInt(getStyle( obj, attr )) + dir;            // 步长
            
            if ( speed > target && dir > 0 ||  speed < target && dir < 0  ) {
                speed = target;
            }
            
            obj.style[attr] = speed + 'px';
            
            if ( speed == target ) {
                clearInterval( obj.timer );
                
                /*
                if ( endFn ) {
                    endFn();
                }
                */
                endFn && endFn();  //只有endFn条件为真就会执行endFn()
                //alert(getStyle(obj, 'left')||3);     //哪边为true就返回哪边  布尔、string、number、object、function
            }
            
        }, 30);
    }
    
    function getStyle ( obj, attr ) { return obj.currentStyle?obj.currentStyle[attr] : getComputedStyle( obj )[attr]; }
    </script>
    通用动画js

     2、ajax封装

    function ajax(method, url, data, success) {
        var xhr = null;
        try {
            xhr = new XMLHttpRequest();
        } catch (e) {
            xhr = new ActiveXObject('Microsoft.XMLHTTP');
        }
        
        if (method == 'get' && data) {
            url += '?' + encodeURI(data);
        }
        
        xhr.open(method,url,true);
        if (method == 'get') {
            xhr.send();
        } else {
            xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
            xhr.send(data);
        }
        
        xhr.onreadystatechange = function() {
            
            if ( xhr.readyState == 4 ) {
                if ( xhr.status == 200 ) {
                    success && success(xhr.responseText);   //定义回调,并传入参数,客户端接收这个参数,并显示出来
                } else {
                    alert('出错了,Err:' + xhr.status);
                }
            }
            
        }
    }
    ajax封装

     //最好将监听放在open、send方法前面调用。xhr.onreadystatechange=function(){...};

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>无标题文档</title>
    <script src="ajax.js"></script>
    <script>
    window.onload = function() {
        
        var oBtn = document.getElementById('btn');
        
        
        oBtn.onclick = function() {
            
            /*ajax({
                url    :    'getNews.php',
                success : function(data) {
                    //...
                }
            });*/
            
            ajax('get','getNews.php','',function(data) {
                var data = JSON.parse( data );
                    
                var oUl = document.getElementById('ul1');
                var html = '';
                for (var i=0; i<data.length; i++) {
                    html += '<li><a href="">'+data[i].title+'</a> [<span>'+data[i].date+'</span>]</li>';
                }
                oUl.innerHTML = html;
            });
            
            setInterval(function() {
                ajax('get','getNews.php','',function(data) {
                    var data = JSON.parse( data );
                        
                    var oUl = document.getElementById('ul1');
                    var html = '';
                    for (var i=0; i<data.length; i++) {
                        html += '<li><a href="">'+data[i].title+'</a> [<span>'+data[i].date+'</span>]</li>';
                    }
                    oUl.innerHTML = html;
                });
            }, 1000);
            
        }
    }
    </script>
    </head>
    
    <body>
        <input type="button" value="按钮" id="btn" />
        <ul id="ul1"></ul>
    </body>
    </html>
    定时刷新

     3、定宽瀑布流

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>无标题文档</title>
    <style>
    body {margin: 0;}
    #ul1 { 1080px; margin: 100px auto 0;}
    li {  247px; list-style: none; float: left; margin-right: 10px; }
    li div {border: 1px solid #000; padding: 10px; margin-bottom: 10px;}
    li div img {  225px; display: block;}
    </style>
    <script src="ajax.js"></script>
    <script>
    window.onload = function() {
        var oUL=document.getElementById('ul1');
        var aLi=oUL.getElementsByTagName('li');
        var iPage=1;
        var b = true;
        
        getList();
        
        function getList() {
            
            ajax('get', 'getPics.php', 'cPage='+iPage, function(data){
                 
                 var data=JSON.parse(data);
                 
                 if ( !data.length ) {
                    //后续没有数据了
                    return ;
                 }
                
                 for(var i=0; i<data.length; i++) {
                       //获取高度最短的li
                        var _index = getShort();
                        
                        //创建3个节点div/img/p
                        var oDiv = document.createElement('div');
                        var oImg = document.createElement('img');
                        var oP = document.createElement('p');
                        oImg.src = data[i].preview;
                        oImg.style.width = '225px';// 同比例缩放
                        oImg.style.height =  data[i].height * ( 225 / data[i].width ) + 'px';
                        oDiv.appendChild( oImg );                
                        oP.innerHTML = data[i].title;
                        oDiv.appendChild( oP );
                        //最后节点永远放在高度最小的那列
                        aLi[_index].appendChild( oDiv );
                 } 
                 b=true;     
            });
        }
        
        
        window.onscroll = function() {
            var _index = getShort();
            var oLi = aLi[_index];
            
            var scrollTop=document.body.scrollTop||document.documentElement.scrollTop;
                
            if(getTop( oLi ) + oLi.offsetHeight < document.documentElement.clientHeight + scrollTop) {
                 if(b) {
                      b=false;
                      iPage++;
                      getList();    
                 }
            }
            
        };
        
        function getShort(){
            var index=0;
            var s=aLi[index].offsetHeight;
            for(var i=0; i<aLi.length; i++) {
                if(s>aLi[i].offsetHeight) {
                    index=i;
                    s=aLi[i].offsetHeight;             
                }
            }
            return index;
        }
         
        //最小的高度obj的top值 
        function getTop(obj) {
            var iTop = 0;
            while(obj) {
                iTop += obj.offsetTop;
                obj = obj.offsetParent;
            }
            return iTop;    
        }
        
    };
    </script>
    </head>
    
    <body>
        <ul id="ul1">
            <li></li>
              <li></li>
            <li></li>
            <li></li>
        </ul>
    </body>
    </html>
    ajax定宽瀑布流

    4、ajax留言(调用后台) 

    另外跨域域名下加'Access-Control-Allow-Origin' 'http://www.a.com'; //这是允许访问该资源的域(服务器设置响应头信息,标准支持,ie不支持)

    jsonp解决跨域

    //ie支持此种跨域,标准不支持
      var oXDomainRequest = new XDomainRequest();
      oXDomainRequest.onload = function() {
       alert(this.responseText);
      }
      oXDomainRequest.open('get', 'http://www.b.com/ajax.php', true);
      oXDomainRequest.send();

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>无标题文档</title>
    <style>
    #div1 { 300px; height: 30px; border: 1px solid #000; position: relative;}
    #div2 { 0; height: 30px; background: #CCC;}
    #div3 { 300px; height: 30px; line-height: 30px; text-align: center; position: absolute; left: 0; top: 0;}
    </style>
    <script>
    window.onload = function() {
        
        var oBtn = document.getElementById('btn');
        var oMyFile = document.getElementById('myFile');
        var oDiv1 = document.getElementById('div1');
        var oDiv2 = document.getElementById('div2');
        var oDiv3 = document.getElementById('div3');
        
        oBtn.onclick = function() {
            
            //alert(oMyFile.value);    //获取到的是file控件的value值,这个内容是显示给你看的文字,不是我们选择的文件
            
            //oMyFile.files file控件中选择的文件列表对象
            //alert(oMyFile.files);
            
            //我们是要通过ajax把oMyFile.files[0]数据发送给后端
            
            /*for (var attr in oMyFile.files[0]) {
                console.log( attr + ' : ' + oMyFile.files[0][attr] );
            }*/
            
            var xhr = new XMLHttpRequest();
            
            //
            xhr.onload = function() {
                //alert(1);
                //var d = JSON.parse(this.responseText);
                
                //alert(d.msg + ' : ' + d.url);
                
                alert('OK,上传完成');
            }
            
            //获得ajax上传对象upload。
            var oUpload = xhr.upload;
            oUpload.onprogress  = function(ev) {
                //console.log(ev.total + ' : ' + ev.loaded);
                //上传比例,loaded 已经上传大小,  total总大小            
                var iScale = ev.loaded / ev.total;            
                oDiv2.style.width = 300 * iScale + 'px';
                oDiv3.innerHTML = Math.floor(iScale * 100) + '%';
                
            }
            //上传一般都用post上传
            xhr.open('post', 'post_file.php', true);
            //设置发送文件的请求头
            xhr.setRequestHeader('X-Request-With', 'XMLHttpRequest;');        
            var oFormData = new FormData();    //通过FormData来构建提交数据
            oFormData.append('file', oMyFile.files[0]);
            xhr.send(oFormData);
            
            
        }
        
    }
    </script>
    </head>
    
    <body>
        <input type="file" id="myFile" /><input type="button" id="btn" value="上传" />
        <div id="div1">
            <div id="div2"></div>
            <div id="div3">0%</div>
        </div>
    <form action="pp_files.php" method="post" enctype="multipart/form-data">
    <!--enctype:multipart/form-data 发送文件头--->
    </form>
    </body>
    </html>
    ajax上传文件
    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>留言本</title>
        <link rel="stylesheet" href="css.css" type="text/css" />
        <script src="ajax.js"></script>
        <script src="guestbook.js"></script>
    </head>
    
    <body>
        <div id="header"></div>
    
        <div id="container">
    
            <div id="list"> 
            <!--<dl>
                    <dt>
                        <strong>zmouse</strong> 说 :
                    </dt>
                    <dd>内容</dd>
                    <dd class="t">
                        <a href="javascript:;" id="support">顶(<span>0</span>)</a>
                         | 
                        <a href="javascript:;" id="oppose">踩(<span>0</span>)</a>
                    </dd>
                </dl>-->
            </div>
            <div id="showMore">显示更多...</div>
    
            <div id="sidebar">
            
                <div id="user" style="margin-bottom: 10px;">
                    <h4><span id="userinfo"></span> <a href="" id="logout">退出</a></h4>
                </div>
            
                <!-- 注册 -->
                <div id="reg">
                    <h4>注册</h4>
                    <div>
                        <p>用户名:<input type="text" name="username" id="username1"></p>
                        <p id="verifyUserNameMsg"></p>
                        <p>密码:<input type="password" name="password" id="password1"></p>
                        <p><input type="button" value="注册" id="btnReg" /></p>
                    </div>
                </div>
    
                <!-- 登陆 -->
                <div id="login">
                    <h4>登陆</h4>
                    <div>
                        <p>用户名:<input type="text" name="username2" id="username2"></p>
                        <p>密码:<input type="password" name="password2" id="password2"></p>
                        <p><input type="button" value="登陆" id="btnLogin" /></p>
                    </div>
                </div>
                
                <!-- 留言发表 -->
                <div id="sendBox">
                    <h4>发表留言</h4>
                    <div>
                        <textarea id="content"></textarea>
                        <input type="button" value="提交" class="btn1" id="btnPost" />
                    </div>
                </div>
            </div>
    
        </div>
        
    </body>
    </html>
    留言HTML
    window.onload = function() {
        
        var oUser = document.getElementById('user');
        var oReg = document.getElementById('reg');
        var oLogin = document.getElementById('login');
        var oUserInfo = document.getElementById('userinfo');
        var oList = document.getElementById('list');
        var iPage = 1;
        
        var oShowMore = document.getElementById('showMore');
        
        var oUsername1 = document.getElementById('username1');
        var oVerifyUserNameMsg = document.getElementById('verifyUserNameMsg');
        
        //初始化
        updateUserStatus();
        
        function updateUserStatus() {
            var uid = getCookie('uid');
            var username = getCookie('username');
            if (uid) {
                //如果是登陆状态
                oUser.style.display = 'block';
                oUserInfo.innerHTML = username;
                oReg.style.display = 'none';
                oLogin.style.display = 'none';
            } else {
                oUser.style.display = 'none';
                oUserInfo.innerHTML = '';
                oReg.style.display = 'block';
                oLogin.style.display = 'block';
            }
        }
        
        showList();
        
        /*
        验证用户名
        get
            guestbook/index.php
                m : index
                a : verifyUserName
                username : 要验证的用户名
            返回
                {
                    code : 返回的信息代码 0 = 没有错误,1 = 有错误
                    message : 返回的信息 具体返回信息
                }
        */
        oUsername1.onblur = function() {
            ajax('get', 'guestbook/index.php', 'm=index&a=verifyUserName&username=' + this.value, function(data) {
                //alert(data);
                var d = JSON.parse(data);
                
                oVerifyUserNameMsg.innerHTML = d.message;
                
                if (d.code) {
                    oVerifyUserNameMsg.style.color = 'red';
                } else {
                    oVerifyUserNameMsg.style.color = 'green';
                }
            });
        }
        
        /*
        用户注册
        get/post
            guestbook/index.php
                m : index
                a : reg
                username : 要注册的用户名
                password : 注册的密码
            返回
                {
                    code : 返回的信息代码 0 = 没有错误,1 = 有错误
                    message : 返回的信息 具体返回信息
                }
        */
        var oPassword1 = document.getElementById('password1');
        var oRegBtn = document.getElementById('btnReg');
        oRegBtn.onclick = function() {
            
            ajax('post', 'guestbook/index.php', 'm=index&a=reg&username='+encodeURI(oUsername1.value)+'&password=' + oPassword1.value, function(data) {
                var d = JSON.parse(data);
                alert(d.message);
                
            });
            
        }
        
        /*
        用户登陆
        get/post
            guestbook/index.php
                m : index
                a : login
                username : 要登陆的用户名
                password : 登陆的密码
            返回
                {
                    code : 返回的信息代码 0 = 没有错误,1 = 有错误
                    message : 返回的信息 具体返回信息
                }
        */
        var oUsername2 = document.getElementById('username2');
        var oPassword2 = document.getElementById('password2');
        var oLoginBtn = document.getElementById('btnLogin');
        oLoginBtn.onclick = function() {
            
            ajax('post', 'guestbook/index.php', 'm=index&a=login&username='+encodeURI(oUsername2.value)+'&password=' + oPassword2.value, function(data) {
                var d = JSON.parse(data);
                alert(d.message);
                
                if (!d.code) {
                    updateUserStatus();
                }
                
            });
            
        }
        
        /*
        用户退出
        get/post
            guestbook/index.php
                m : index
                a : logout
            返回
                {
                    code : 返回的信息代码 0 = 没有错误,1 = 有错误
                    message : 返回的信息 具体返回信息
                }
        */
        var oLogout = document.getElementById('logout');
        oLogout.onclick = function() {
            
            ajax('get', 'guestbook/index.php', 'm=index&a=logout', function(data) {
                
                var d = JSON.parse(data);
                alert(d.message);
                
                if (!d.code) {
                    //退出成功
                    updateUserStatus();
                }
                
            });
            
            return false;
            
        }
        
        /*
        留言
        post
            guestbook/index.php
                m : index
                a : send
                content : 留言内容
            返回
                {
                    code : 返回的信息代码 0 = 没有错误,1 = 有错误
                    data : 返回成功的留言的详细信息
                        {
                            cid : 留言id    
                            content : 留言内容 
                            uid : 留言人的id
                            username : 留言人的名称
                            dateline : 留言的时间戳(秒)
                            support : 当前这条留言的顶的数量
                            oppose : 当前这条留言的踩的数量
                        }
                    message : 返回的信息 具体返回信息
                }
        */
        var oContent = document.getElementById('content');
        var oPostBtn = document.getElementById('btnPost');
        oPostBtn.onclick = function() {
            
            ajax('post', 'guestbook/index.php', 'm=index&a=send&content='+encodeURI(oContent.value), function(data) {
                
                var d = JSON.parse(data);
                //alert(d.message);
                
                if (!d.code) {
                    //添加当前留言到列表中
                    createList(d.data, true);
                }
                
            });
            
        }
        
        //从后台返回的json的data
        function createList(data, insert) {
            var oDl = document.createElement('dl');
                    
            var oDt = document.createElement('dt');
            var oStrong = document.createElement('strong');
            oStrong.innerHTML = data.username;
            oDt.appendChild(oStrong);
            
            var oDd1 = document.createElement('dd');
            oDd1.innerHTML = data.content;
            
            var oDd2 = document.createElement('dd');
            oDd2.className = 't';
            var oA1 = document.createElement('a');
            oA1.href = '';
            oA1.innerHTML = '顶(<span>'+data.support+'</span>)';
            var oA2 = document.createElement('a');
            oA2.href = '';
            oA2.innerHTML = '踩(<span>'+data.oppose+'</span>)';
            oDd2.appendChild(oA1);
            oDd2.appendChild(oA2);
            
            oDl.appendChild(oDt);
            oDl.appendChild(oDd1);
            oDl.appendChild(oDd2);
            
            
            //oList存在留言就在oList前面插入留言insertBefore,否则直接插入留言appendChild
            if (insert && oList.children[0]) {
                oList.insertBefore(oDl, oList.children[0]);
            } else {
                oList.appendChild(oDl);
            }
        }
        
        //点击显示更多的内容
        oShowMore.onclick = function() {
            iPage++;
            showList();
        }
        
        function showList() {
            /*
            初始化留言列表
            get
                guestbook/index.php
                    m : index
                    a : getList
                    page : 获取的留言的页码,默认为1
                    n : 每页显示的条数,默认为10
                返回
                    {
                        code : 返回的信息代码 0 = 没有错误,1 = 有错误
                        data : 返回成功的留言的详细信息
                            {
                                cid : 留言id    
                                content : 留言内容 
                                uid : 留言人的id
                                username : 留言人的名称
                                dateline : 留言的时间戳(秒)
                                support : 当前这条留言的顶的数量
                                oppose : 当前这条留言的踩的数量
                            }
                        message : 返回的信息 具体返回信息
                    }
            */
            ajax('get', 'guestbook/index.php', 'm=index&a=getList&n=2&page=' + iPage, function(data) {
                
                var d = JSON.parse(data);
                
                var data = d.data;
                
                if (data) {
                    for (var i=0; i<data.list.length; i++) {
                        createList(data.list[i]);
                    }
                } else {
                    if (iPage == 1) {
                        oList.innerHTML = '现在还没有留言,快来抢沙发...';
                    }
                    oShowMore.style.display = 'none';
                }
                
            });
        }
    };
    
    function getCookie(key) {
        var arr1 = document.cookie.split('; ');
        for (var i=0; i<arr1.length; i++) {
            var arr2 = arr1[i].split('=');
            if (arr2[0]==key) {
                return arr2[1];
            }
        }
    }
    留言ajax

    5、canvas旋转并缩放

    window.onload=function(){
       var can=document.getElementById('canvas');
       var canvas=can.getContext('2d');
       var num=0;
       var num2=0;
       var value=1;
       canvas.translate(100,100);
       
       setInterval(function(){         
             num++;
             canvas.save();         
             canvas.clearRect(0,0,can.width,can.height);
             if(num2==100) vlaue=-1;
             else if(num2==0) value=1;
             num2+=value;
             canvas.translate(-50,-50);
             canvas.rotate(num*Math.PI/180); 
             canvas.scale(num2*1/50,num2*1/50);
             canvas.fillRect(0,0,100,100,false);
             canvas.restore();
             canvas.stroke();
       }, 30);
       
    };
    旋转缩放
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>无标题文档</title>
    <script>
    window.onload=function(){
       var aInput=document.getElementsByTagName('input');
       var oImg=document.getElementById('img1');
       
       var yImg=new Image();
       
       yImg.onload=function() {
            draw(oImg);
       };
       
       yImg.src=oImg.src;
       
       function draw(obj){
           var oC=document.createElement('canvas');
           var canvas=oC.getContext('2d');
           var iNow=1;
           oC.width=obj.width;
           oC.height=obj.height;
           obj.parentNode.replaceChild(oC,obj);
           canvas.drawImage(obj,0,0);
           
           aInput[1].onclick=function(){
               
               if(iNow==3) iNow=0; else iNow++;
               
               toChange();
           };
           aInput[0].onclick=function(){
               if(iNow==0) iNow=3; else iNow--;
               toChange();
           };
           function toChange(){
               switch(iNow){
                   case 1:
                       oC.width=obj.height;
                       oC.height=obj.width;
                       canvas.rotate(90*Math.PI/180);
                       canvas.drawImage(obj,0,-obj.height);
                   break;
                   
                   case 2:
                       oC.width=obj.width;
                       oC.height=obj.height;
                       canvas.rotate(180*Math.PI/180);
                       canvas.drawImage(obj,-obj.width,-obj.height);
                   break;    
                   case 3:
                       oC.width=obj.height;
                       oC.height=obj.width;
                       canvas.rotate(270*Math.PI/180);
                       canvas.drawImage(obj,-obj.width,0);
                   break;
                   case 0:
                       oC.width=obj.width;
                       oC.height=obj.height;
                       canvas.rotate(0*Math.PI/180);
                       canvas.drawImage(obj,0,0);
                   break;
               }
           }
       }
    };
    </script>
    </head>
    
    <body>
    <input type="button" value="左"/>
    <input type="button" value="右"/>
    <div><img src="iBannerText.png" id="img1" /></div>
    </body>
    </html>
    旋转
    window.onload=function(){
        var oc=document.getElementById('canvas');
        var canvas=oc.getContext('2d');
        canvas.fillRect(0,0,100,100);
        var oImg=canvas.getImageData(0,0,100,100);  //返回图像像素
        
        for(var i=0; i<oImg.width*oImg.height; i++) {
            oImg.data[4*i]=255;   //data数组中的每个像素都rgba四个构成, length=4*w*h
            oImg.data[4*i+1]=0;
            oImg.data[4*i+2]=0;
            oImg.data[4*i+3]=50;
        }
        
        canvas.putImageData(oImg, 100,100); //绘制图像像素至canvas中
    };
    canva像素操作
     1 <!doctype html>
     2 <html>
     3 <head>
     4 <meta charset="utf-8">
     5 <title>无标题文档</title>
     6 <script>
     7 window.onload=function(){
     8     var oc=document.getElementById('canvas');
     9     var canvas=oc.getContext('2d');
    10     
    11     var aLi=document.getElementsByTagName('li');
    12     for(var i=0; i<aLi.length; i++){
    13         aLi[i].onclick=function() {
    14             var str=this.innerHTML;
    15             var h=180;
    16             canvas.clearRect(0, 0, oc.width, oc.height);
    17             canvas.font=h+'px impact';
    18             canvas.textBaseline='top';
    19             canvas.fillStyle='red';
    20             var w=canvas.measureText(str).width;
    21             canvas.fillText(str, (oc.width-w)/2, (oc.height-h)/2);
    22             var oImg=canvas.getImageData((oc.width-w)/2, (oc.height-h)/2, w,h);
    23             canvas.clearRect(0,0,oc.width,oc.height);
    24             var arr=randomArr(w*h,w*h/10);
    25             var newImg=canvas.createImageData(w,h);  //创建一个新的img图片像素
    26             for(var i=0; i<arr.length; i++) {
    27                 //旧的像素数组,赋值给新的像素数组当中
    28                 newImg.data[4*arr[i]]=oImg.data[4*arr[i]];
    29                 newImg.data[4*arr[i]+1]=oImg.data[4*arr[i]+1];
    30                 newImg.data[4*arr[i]+2]=oImg.data[4*arr[i]+2];
    31                 newImg.data[4*arr[i]+3]=oImg.data[4*arr[i]+3];
    32             }
    33             
    34             //绘制像素图片到canvas中
    35             canvas.putImageData(newImg, (oc.width-w)/2, (oc.height-h)/2);
    36         
    37         };
    38     }
    39     
    40     //函数功能:iAll,iNow(原数组长度,新数组长度) 返回新的数组
    41     function randomArr(iAll, iNow){
    42         var arr=[];
    43         var newArr=[];
    44         for(var i=0; i<iAll; i++) {
    45            arr.push(i);
    46         }
    47         for(var i=0; i<iNow; i++) {
    48            newArr.push(arr.splice(Math.floor(Math.random()*arr.length),1));
    49         }
    50         return newArr;
    51     }
    52     
    53 };
    54 </script>
    55 </head>
    56 
    57 <body>
    58     
    59 <canvas id="canvas" width=500 height=500></canvas>
    60 <ul style="float:left">
    61 <li>我</li>
    62 <li>爱</li>
    63 <li>你</li>
    64 <li>吗</li>
    65 </ul>
    66 </body>
    67 </html>
    图片像素生产10%的图片文字
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>无标题文档</title>
    <script>
    window.onload=function(){
        var oc=document.getElementById('canvas');
        var canvas=oc.getContext('2d');
        
        var aLi=document.getElementsByTagName('li');
        for(var i=0; i<aLi.length; i++){
            aLi[i].onclick=function() {
                var str=this.innerHTML;
                var h=180;
                var timer=null;
                var iNow=0; 
                clearInterval(timer);
                canvas.clearRect(0, 0, oc.width, oc.height);
                canvas.font=h+'px impact';
                canvas.textBaseline='top';
                canvas.fillStyle='red';
                var w=canvas.measureText(str).width;
                canvas.fillText(str, (oc.width-w)/2, (oc.height-h)/2);
                var oImg=canvas.getImageData((oc.width-w)/2, (oc.height-h)/2, w,h);
                canvas.clearRect(0,0,oc.width,oc.height);
                var arr=randomArr(w*h,w*h/10);
                var newImg=canvas.createImageData(w,h);  //创建一个新的img图片像素
                timer=setInterval(function(){
                    for(var i=0; i<arr[iNow].length; i++) {
                        //旧的像素数组,赋值给新的像素数组当中
                        newImg.data[4*arr[iNow][i]]=oImg.data[4*arr[iNow][i]];
                        newImg.data[4*arr[iNow][i]+1]=oImg.data[4*arr[iNow][i]+1];
                        newImg.data[4*arr[iNow][i]+2]=oImg.data[4*arr[iNow][i]+2];
                        newImg.data[4*arr[iNow][i]+3]=oImg.data[4*arr[iNow][i]+3];
                       }
                        //绘制像素图片到canvas中
                    canvas.putImageData(newImg, (oc.width-w)/2, (oc.height-h)/2);       
                    if(iNow==9)  {
                        iNow=0;
                        clearInterval(timer);
                    }
                    else iNow++;            
                }, 200);
                            
            };
        }
        
        //函数功能:iAll,iNow(原数组长度,新数组长度) 返回复合的数组,allArr存的就是10个元素,每个元素也是一位数组,leng=w*h;
        function randomArr(iAll, iNow){
            var arr=[];
            var allArr=[];
            for(var i=0; i<iAll; i++) {
               arr.push(i);
            }
            
            for(var j=0; j<iAll/iNow; j++) {
                var newArr=[];
                for(var i=0; i<iNow; i++) {
                   newArr.push(arr.splice(Math.floor(Math.random()*arr.length),1));
                }
                allArr.push(newArr);
            }
            
            return allArr;
        }
        
    };
    </script>
    </head>
    
    <body>
        
    <canvas id="canvas" width=500 height=500></canvas>
    <ul style="float:left">
    <li>我</li>
    <li>爱</li>
    <li>你</li>
    <li>吗</li>
    </ul>
    </body>
    </html>
    动态生产每次10%文字像素
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>无标题文档</title>
    <script>
    window.onload=function(){
        var oc=document.getElementById('canvas');
        var canvas=oc.getContext('2d');
        canvas.fillRect(0,0,100,100);
        var oImg=canvas.getImageData(0,0,100,100);
        alert(getXY(oImg, 3, 5));
        for(var i=0; i<oImg.width; i++){
            setXY(oImg, i, 5, [255,0,0,255]);
            canvas.putImageData(oImg,100,100);
        }
        function getXY(obj, x, y){
            var arr=[];
            var w=obj.width;
            var h=obj.height;
            var d=obj.data;
            
            arr[0]=d[4*(y*w+x)];
            arr[1]=d[4*(y*w+x)+1];
            arr[2]=d[4*(y*w+x)+2];
            arr[3]=d[4*(y*w+x)+3];
            return arr;
        }
        
        function setXY(obj, x, y,color){
            var arr=[];
            var w=obj.width;
            var h=obj.height;
            var d=obj.data;
            
            d[4*(y*w+x)]=color[0];
            d[4*(y*w+x)+1]=color[1];
            d[4*(y*w+x)+2]=color[2];
            d[4*(y*w+x)+3]=color[3];
        }
    }
    </script>
    </head>
    
    <body>
         
    <canvas id="canvas" width=500 height=500></canvas>
    </body>
    </html>
    封装通过xy坐标生成像素图片
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>无标题文档</title>
    <script>
    window.onload=function(){
        var oc=document.getElementById('canvas');
        var canvas=oc.getContext('2d');
        var yImg=new Image();
        yImg.onload=function() {
            draw(this);
        };
        yImg.src='2.png';
        
        function getXY(obj, x, y){
            var arr=[];
            var w=obj.width;
            var h=obj.height;
            var d=obj.data;
            
            arr[0]=d[4*(y*w+x)];
            arr[1]=d[4*(y*w+x)+1];
            arr[2]=d[4*(y*w+x)+2];
            arr[3]=d[4*(y*w+x)+3];
            return arr;
        }
        
        function setXY(obj, x, y,color){
            var arr=[];
            var w=obj.width;
            var h=obj.height;
            var d=obj.data;
            
            d[4*(y*w+x)]=color[0];
            d[4*(y*w+x)+1]=color[1];
            d[4*(y*w+x)+2]=color[2];
            d[4*(y*w+x)+3]=color[3];
        }
        
        function draw(obj) {
            oc.width=obj.width;
            //oc.height=2*obj.height;
            canvas.drawImage(obj,0,0,obj.width, obj.height);
            var oImg=canvas.getImageData(0,0,obj.width, obj.height);
            var w=oImg.width;
            var h=oImg.height;
            var newImg=canvas.createImageData(w,h);
            //先循环列
            for(var i=0; i<h; i++) {
                //循环行
                for(var j=0; j<w; j++) {
                    var result=[];
                    var color=getXY(oImg, j, i);
                    result[0]=255-color[0];
                    result[1]=255-color[1];
                    result[2]=255-color[2];
                    result[3]=255*i/h;
                    setXY(newImg, j,h-i, result);
                }
            }
            
            canvas.putImageData(newImg, 0, obj.height);
        }
        
        
    };
    </script>
    </head>
    
    <body>
    
    <canvas id="canvas"></canvas>
    </body>
    </html>
    canvas实现图片反色、渐变、倒影
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>无标题文档</title>
    <script>
    window.onload=function(){
        var oc=document.getElementById('canvas');
        var canvas=oc.getContext('2d');
        var yImg=new Image();
        yImg.onload=function() {
            draw(this);
        };
        yImg.src='2.png';
        
        function getXY(obj, x, y){
            var arr=[];
            var w=obj.width;
            var h=obj.height;
            var d=obj.data;
            
            arr[0]=d[4*(y*w+x)];
            arr[1]=d[4*(y*w+x)+1];
            arr[2]=d[4*(y*w+x)+2];
            arr[3]=d[4*(y*w+x)+3];
            return arr;
        }
        
        function setXY(obj, x, y,color){
            var arr=[];
            var w=obj.width;
            var h=obj.height;
            var d=obj.data;
            
            d[4*(y*w+x)]=color[0];
            d[4*(y*w+x)+1]=color[1];
            d[4*(y*w+x)+2]=color[2];
            d[4*(y*w+x)+3]=color[3];
        }
        
        function draw(obj) {
            //num分块图片 w/num, h/num
            var num=10;
            oc.width=obj.width;
            //oc.height=2*obj.height;
            canvas.drawImage(obj,0,0,obj.width, obj.height);
            var oImg=canvas.getImageData(0,0,obj.width, obj.height);
            var w=oImg.width;
            var h=oImg.height;
            var newImg=canvas.createImageData(w,h);
            //具体分块
            var stepW=w/num;
            var stepH=h/num;
            for(var i=0; i<stepH; i++) {
                for(var j=0; j<stepW; j++) {
                    //提取颜色
                    var color=getXY(oImg, j*num+Math.floor(Math.random()*num),i*num+Math.floor(Math.random()*num));
                    //根据num块循环,块是个二维数组(如如很多方格)
                    for(var k=0; k<num; k++) {
                        for(var l=0; l<num; l++) {
                            setXY(newImg, j*num+l, i*num+k, color);
                        }
                    }
                }
            }
            canvas.putImageData(newImg,0, obj.height);
        }
        
        
    };
    </script>
    </head>
    
    <body>
    
    <canvas id="canvas"></canvas>
    </body>
    </html>
    canvas实现图片马赛克

    6、html5实现的播放器

    属性:
    controls  :   显示或隐藏用户控制界面
    autoplay  :  媒体是否自动播放
    loop  : 媒体是否循环播放
    currentTime  :  开始到播放现在所用的时间
    duration  :  媒体总时间(只读)
    volume  :   0.0-1.0的音量相对值
    muted  :   是否静音
    autobuffer  :   开始的时候是否缓冲加载,autoplay的时候,忽略此属性
    paused  :   媒体是否暂停(只读)
    ended   :   媒体是否播放完毕(只读)
    error   :  媒体发生错误的时候,返回错误代码 (只读)
    currentSrc  :   以字符串的形式返回媒体地址(只读)
    poster  :   视频播放前的预览图片
    width、height  :   设置视频的尺寸
    videoWidth、 videoHeight  :   视频的实际尺寸(只读)
    
    方法:
    play()  :  媒体播放
    pause()  :  媒体暂停
    load()  :  重新加载媒体
    事件:
    loadstart progress suspend emptied stalled play pause loadedmetadata loadeddata waiting playing canplay canplaythrough seeking seeked timeupdate ended ratechange durationchange volumechange
    HTML5 viedo属性方法事件
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文档</title>
    <style>
    *{ margin:0; padding:0;}
    #div1{ 300px; height:30px; background:#666; overflow:hidden; position:relative;}
    #div2{ 60px; height:30px; background:red; position:absolute; left:0; top:0;}
    
    #div3{ 300px; height:10px; background:#666; overflow:hidden; position:relative; top:10px;}
    #div4{ 60px; height:10px; background:yellow; position:absolute; left:240px; top:0;}
    
    </style>
    <script>
    
    window.onload = function(){
        var oV = document.getElementById('v1');
        var aInput = document.getElementsByTagName('input');
        
        var oDiv1 = document.getElementById('div1');
        var oDiv2 = document.getElementById('div2');
        var oDiv3 = document.getElementById('div3');
        var oDiv4 = document.getElementById('div4');
        
        var disX = 0;
        var disX2 = 0;
        
        var timer = null;
        
        aInput[0].onclick = function(){
            
            if( oV.paused ){
                
                oV.play();
                
                this.value = '暂停';
                
                nowTime();
                timer = setInterval(nowTime,1000);
                
            }
            else{
                
                oV.pause();
                
                this.value = '播放';
                
                clearInterval(timer);
                
            }
            
        };
        
        
        aInput[2].value = changeTime(oV.duration);
        
        aInput[3].onclick = function(){
            
            
            if( oV.muted ){
                
                oV.volume = 1;
                
                this.value = '静音';
                
                oV.muted = false;
                
            }
            else{
                
                oV.volume = 0;
                
                this.value = '取消静音';
                
                oV.muted = true;
                
            }
            
        };
        
        aInput[4].onclick = function(){
            oV.mozRequestFullScreen();
        };
        
        
        function nowTime(){
            
            aInput[1].value = changeTime(oV.currentTime);
            
            var scale = oV.currentTime/oV.duration;
            
            oDiv2.style.left = scale * 240 + 'px';
            
        }
        
        
        function changeTime(iNum){
            
            iNum = parseInt( iNum );
            
            var iH = toZero(Math.floor(iNum/3600));
            var iM = toZero(Math.floor(iNum%3600/60));
            var iS = toZero(Math.floor(iNum%60));
            
            return iH + ':' +iM + ':' + iS;
            
        }
        
        function toZero(num){
            if(num<=9){
                return '0' + num;
            }
            else{
                return '' + num;
            }
        }
        
        
        oDiv2.onmousedown = function(ev){
            var ev = ev || window.event;
            disX = ev.clientX - oDiv2.offsetLeft;
            
            document.onmousemove = function(ev){
                var ev = ev || window.event;
                
                var L = ev.clientX - disX;
                
                if(L<0){
                    L = 0;
                }
                else if(L>oDiv1.offsetWidth - oDiv2.offsetWidth){
                    L = oDiv1.offsetWidth - oDiv2.offsetWidth;
                }
                
                oDiv2.style.left = L + 'px';
                
                
                var scale = L/(oDiv1.offsetWidth - oDiv2.offsetWidth);
                
                oV.currentTime = scale * oV.duration;
                
                nowTime();
                
            };
            document.onmouseup = function(){
                document.onmousemove = null;
            };
            return false;
        };
        
        
        oDiv4.onmousedown = function(ev){
            var ev = ev || window.event;
            disX2 = ev.clientX - oDiv4.offsetLeft;
            
            document.onmousemove = function(ev){
                var ev = ev || window.event;
                
                var L = ev.clientX - disX2;
                
                if(L<0){
                    L = 0;
                }
                else if(L>oDiv3.offsetWidth - oDiv4.offsetWidth){
                    L = oDiv3.offsetWidth - oDiv4.offsetWidth;
                }
                
                oDiv4.style.left = L + 'px';
                
                var scale = L/(oDiv3.offsetWidth - oDiv4.offsetWidth);
                oV.volume = scale;
                
            };
            document.onmouseup = function(){
                document.onmousemove = null;
            };
            return false;
        };
        
    };
    
    </script>
    </head>
    
    <body>
    <video id="v1">
    
        <source src="Intermission-Walk-in.ogv"></source>
        <source src="Intermission-Walk-in_512kb.mp4"></source>
    
    </video><br />
    <input type="button" value="播放" />
    <input type="button" value="00:00:00" />
    <input type="button" value="00:00:00" />
    <input type="button" value="静音" />
    <input type="button" value="全屏" />
    <div id="div1">
        <div id="div2"></div>
    </div>
    <div id="div3">
        <div id="div4"></div>
    </div>
    
    </body>
    </html>
    HTML5播放器

    7、地理位置、定位(后续)

  • 相关阅读:
    git
    fragment
    Builder模式
    代码混淆
    android studio快捷键
    小知识点
    angular组件使用
    英语摘要2019-6-4
    英语笔记2019-4-3
    搭建Eureka注册中心时遇到的问题
  • 原文地址:https://www.cnblogs.com/codc-5117/p/5578605.html
Copyright © 2011-2022 走看看