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贯彻超过浏览器添加事件及移除事件如何做才最好优异?

相似的匹配做法,如下:

跨越浏览器添加事件

//跨浏览器添加事件
    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);
    }
}

推荐写法

    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
Up

3.Ajax之所以jsonp方式跨域发送请求小实例

分明,Ajax是通过创设XMLHttpRequest对象要ActiveXObject来连续服务器、发送请求和响应数据,但它们也未能够跨域。而于分布式系统中我们同时欲跨域发送接受多少,于是jsonp出现了…

其是同等种跨域请求方式,主要行使了script标签里之src属性,该属性可以跨域发送请求,然后服务器返回js代码,网页端便应其信息,然后我们可以本着那个传过来的js代码做拍卖提取其中的音讯。

jsonp发送请求单待在src后面长“?callback=函数曰”就可以,例如“http://www.item.com/list?callback=myfunction“,则单纯待在服务端接受参数myfunction并以函数名叫及思念使赶回的数码拼接就得像当java中作应该要,可以抱参数callback的值myfunction,再并入接成myfunction+”(“+data+”)”格式返回就执行,在前者写及名函数接受data并拍卖就得了。但当jquery中对jsonp进行了打包,返回函数就是success,数据为因而success接受。

例如:

前端代码:

//发送请求  
$.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";
}

 

相关文章