Web前端常用代码笔记整理(0二)

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*/

贰.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

Ajax,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.HTML伍Canvas标签绘制图形

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";
}

 

相关文章