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";
}
    原文作者:风雨后见彩虹
    原文地址: https://segmentfault.com/a/1190000007844870
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞