Web前端經常使用代碼筆記整理(02)

1.canvas圖片預加載及進度條的實現

/*star
 *loading模塊
 *實現圖片的預加載,並顯示進度條
 *參數:圖片數組對象,加載完成的回調函數
 */
function loadImages(sources,callback){    
    var loadedImages = 0;    
    var numImages = 0;  
    ctx.font='14px bold';
    ctx.lineWidth=5;
    var clearWidth=canvas.width;
    var clearHeight=canvas.height;
    // get num of sources    
    for (var src in sources) {    
        numImages++;    
    }    
    for (var src in sources) {    
        images[src] = new Image();
        //當一張圖片加載完成時執行    
        images[src].onload = function(){ 
            //重繪一個進度條
            ctx.clearRect(0,0,clearWidth,clearHeight);
            ctx.fillText('Loading:'+loadedImages+'/'+numImages,200,280);
            ctx.save();
            ctx.strokeStyle='#555';
            ctx.beginPath();
            ctx.moveTo(200,300);
            ctx.lineTo(600,300);
            ctx.stroke();
            ctx.beginPath();
            ctx.restore();
            ctx.moveTo(200,300);
            ctx.lineTo(loadedImages/numImages*400+200,300);  
            ctx.stroke();
            //當全部圖片加載完成時,執行回調函數callback
            if (++loadedImages >= numImages) {    
                callback();    
            }    
        };  
        //把sources中的圖片信息導入images數組  
        images[src].src = sources[src];    
    }    
}    
//定義預加載圖片數組對象,執行loading模塊
window.onload = function(){    
    var sources = {    
        PaperBoy1: "images/run/PaperBoy1.png",    
        PaperBoy2: "images/run/PaperBoy2.png", 
        PaperBoy3: "images/run/PaperBoy3.png",    
        PaperBoy4: "images/run/PaperBoy4.png",  
        PaperBoy5: "images/run/PaperBoy5.png",    
        PaperBoy6: "images/run/PaperBoy6.png",  
        PaperBoy7: "images/run/PaperBoy7.png",    
        PaperBoy8: "images/run/PaperBoy8.png",  
        PaperBoy9: "images/run/PaperBoy9.png",    
        PaperBoy10: "images/run/PaperBoy10.png",  
        PaperBoy11: "images/run/PaperBoy11.png",    
        PaperBoy12: "images/run/PaperBoy12.png",   
        PaperBoy13: "images/run/PaperBoy13.png",    
        PaperBoy14: "images/run/PaperBoy14.png", 
        PaperBoy15: "images/run/PaperBoy15.png",    
        PaperBoy16: "images/run/PaperBoy16.png",  
        PaperBoy17: "images/run/PaperBoy17.png",    
        PaperBoy18: "images/run/PaperBoy18.png",  
        PaperBoy19: "images/run/PaperBoy19.png",    
        PaperBoy20: "images/run/PaperBoy20.png",  
        PaperBoy21: "images/run/PaperBoy21.png",    
        PaperBoy22: "images/run/PaperBoy22.png",  
        PaperBoy23: "images/run/PaperBoy23.png",    
        PaperBoy24: "images/run/PaperBoy24.png", 
        _Street:'images/_Street.png',
        AD:'images/AD.png',
        building:'images/building.png',
        cloud:'images/cloud.png'
    };    
    //執行圖片預加載,加載完成後執行main
    loadImages(sources,main);    
};   
/*end*/

2.JS實現跨瀏覽器添加事件與移除事件怎樣作才最優?

通常的兼容作法,以下:javascript

跨瀏覽器添加事件html

//跨瀏覽器添加事件
    function addEvent(obj,type,fn){
        if(obj.addEventListener){
            obj.addEventListener(type,fn,false);
        }else if(obj.attachEvent){//IE
            obj.attchEvent('on'+type,fn);
        }
    }

跨瀏覽器移除事件前端

//跨瀏覽器移除事件
function removeEvent(obj,type,fn){
    if(obj.removeEventListener){
        obj.removeEventListener(type,fn,false);
    }else if(obj.detachEvent){//兼容IE
        obj.detachEvent('on'+type,fn);
    }
}

推薦寫法java

function addEvent( obj, type, fn ) {
      if ( obj.attachEvent ) {
        obj['e'+type+fn] = fn;
        obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
        obj.attachEvent( 'on'+type, obj[type+fn] );
      } else
        obj.addEventListener( type, fn, false );
    }
    function removeEvent( obj, type, fn ) {
      if ( obj.detachEvent ) {
        obj.detachEvent( 'on'+type, obj[type+fn] );
        obj[type+fn] = null;
      } else
        obj.removeEventListener( type, fn, false );
    }

參考地址
addEvent() recoding contest entry
addEvent() – Follow Upjquery

3.Ajax用jsonp方式跨域發送請求小實例

衆所周知,Ajax是經過建立XMLHttpRequest對象或ActiveXObject來鏈接服務器、發送請求以及響應數據,但它卻不能跨域。而在分佈式系統中咱們又須要跨域發送接受數據,因而jsonp出現了...web

它是一種跨域請求方式,主要利用了script標籤裏的src屬性,該屬性能夠跨域發送請求,而後服務器返回js代碼,網頁端便響應其信息,而後咱們能夠對其傳過來的js代碼作處理提取其中的信息。ajax

jsonp發送請求只需在src後面添加「?callback=函數名」就能夠,例如「http://www.item.com/list?callback=myfunction",則只需在服務端接受參數myfunction並將函數名與想要返回的數據拼接就能夠例如在java中響應該請求,能夠獲取參數callback的值myfunction,再拼接成myfunction+"("+data+")"格式返回就行,在前端寫同名函數接受data並處理就能夠了。但在jquery中對jsonp進行了封裝,返回函數就是success,數據也用success接受。json

例如:canvas

前端代碼:api

//發送請求  
$.ajax({  
   //url:"http://localhost:8081/rest/itemcat/list?callback=getMessage",  
    url:"http://localhost:8081/rest/itemcat/message",      
    type:"get",  
    cache:false,  
    dataType:"jsonp",  
    jsonp:"callback", //這裏定義了callback的參數名稱,以便服務獲取callback的函數名即getMessage  
    jsonpCallback:"getMessage", //這裏定義了jsonp的回調函數  
    success:function(data){  
        alert("success:"+data);  
    },  
    error:function(){  
        alert("發生異常");  
    }  
});  

function getMessage(jsonp){  
    alert("message:"+jsonp);  
}

這樣發出的請求爲:http://localhost:8081/rest/itemcat/message?callback=getMessage
jsonp:"callback",
jsonpCallback:"getMessage",
這兩個參數的值會自動拼接在url後面,因此用jquery的$.ajax方法發出的url能夠不用在後面添加callback=getMessag,返回函數則變爲了success而不是getMessage

4.使用高德地圖API建立地圖以及獲取當前地址經緯度

建立API地圖帶有點標記

<script src="http://webapi.amap.com/maps?v=1.4.1&key=bcf87f3263f98cc37309298bca20c622"></script>
<script type="text/javascript">
    // 實例化點標記
 function addMarker() {
        marker = new AMap.Marker({
            icon: "http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
            position: [116.41, 39.91]
        });
        marker.setMap(map);
    }

 var map = new AMap.Map('container', {
        resizeEnable: true,
        center: [116.40, 39.91],
        zoom: 13
    });
 addMarker();
</script>

根據瀏覽器定位獲取當前經緯度

<div id="container_display"></div>
<script src="https://webapi.amap.com/maps?v=1.4.1&key=bcf87f3263f98cc37309298bca20c622"></script>
<script>
function loadingCurrentPosition(callback){
    
    document.getElementById('container_display').innerHTML = '';
      //加載地圖,調用瀏覽器定位服務
    map = new AMap.Map('container_display', {
        resizeEnable: true
    });
    map.plugin('AMap.Geolocation', function() {
        geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位,默認:true
            timeout: 10000,          //超過10秒後中止定位,默認:無窮大
            buttonOffset: new AMap.Pixel(10, 20),//定位按鈕與設置的停靠位置的偏移量,默認:Pixel(10, 20)
            zoomToAccuracy: true,      //定位成功後調整地圖視野範圍使定位位置及精度範圍視野內可見,默認:false
            buttonPosition:'RB'
        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
        AMap.event.addListener(geolocation, 'error', onError);      //返回定位出錯信息
    });
    //解析定位結果
    function onComplete(data) {
        var getLngdata = data.position.getLng();
        var getLatdata = data.position.getLat();
        if(callback){
            callback(getLngdata,getLatdata); //回調參數中傳遞經度與緯度
        }
    }
    //解析定位錯誤信息
    function onError(data) {
        alert('定位失敗');
    }
}

$(function(){
    var getLng = ''; //存經度
    var getLat = ''; //存緯度
    //默認加載一次自動獲取當前人的位置
    loadingCurrentPosition(function(lngdata,Latdata){
        getLng = lngdata;
        getLat = Latdata;
    });
    $(".getCurrentPosition").on('click',function(){
        loadingCurrentPosition(function(lngdata,Latdata){
            getLng = lngdata;
            getLat = Latdata;
        });
    });
})

</script>

高德地圖根據瀏覽器定位獲取當前經緯度API案例地址:http://lbs.amap.com/api/javascript-api/example/location/browser-location
高德開放平臺:http://lbs.amap.com/api

5.JS建立canvas學習小例代碼

1.HTML5中的Canvas標籤的建立

window.onload = function(){
     createCanvas();
}
function createCanvas(){
    var canvas_width= 200, canvas_height = 200;
    document.body.innerHTML = "<canvas id=\"canvas\" width=\""+canvas_width+"\" height=\""+canvas_height+"\"></canvas>";
}

2.HTML5Canvas標籤繪製圖形

var canvas_width= 500, canvas_height = 500;
var mycanvas, context;
window.onload = function(){
    createCanvas();
    drawRect();
}
function createCanvas(){
   document.body.innerHTML = "<canvas id=\"mycanvas\" width=\""+canvas_width+"\" height=\""+canvas_height+"\"></canvas>";
   mycanvas = document.getElementById("mycanvas");
   context = mycanvas.getContext("2d");
}
 
function drawRect(){
    context.fillStyle ="#FF0000";
    //context.rotate(45);//旋轉45度
    //context.translate(200,200);//移動
    //context.scale(2,0.5);//縮放
    context.fillRect(0,0,200,200);
 }

3.HTML5Canvas標籤繪製圖片

var canvas_width= 500, canvas_height = 500;
var mycanvas, context;
window.onload = function(){
    createCanvas();
    drawImage();
}
function createCanvas(){
    document.body.innerHTML = "<canvas id=\"mycanvas\" width=\""+canvas_width+"\" height=\""+canvas_height+"\"></canvas>";
    mycanvas = document.getElementById("mycanvas");
    context = mycanvas.getContext("2d");
}
 
function drawImage(){
    var img = new Image();
    img.onload = function(){
        context.drawImage(img,0,0);
    }
     img.src = "1.png";
}
相關文章
相關標籤/搜索