首页 > 求大神指点:我要把图片放在canvas上在插入到img中,但是不知为什么出错了

求大神指点:我要把图片放在canvas上在插入到img中,但是不知为什么出错了

1.拿个图片站位 ,在img里面设置一个 叫 data-src=""放图片路径 把图片缓存到localStorage里

2.
<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">
<title>Document</title>
<style>
    .cc{
        width:140px;
        height: 108px;
        background: #ccc;
    }
</style>

</head>
<body>

<div class='cc' id="1">
    <img data-src="./bar.gif" class="lazyload" id="data-src-1" alt="">
</div>
<script src="./jquery-1.11.3.min.js"></script>

<script>
$(function(){

renderCvs($('.cc'));

});

var renderCvs=function(parent,max){
    var lazyloadImage=$('.lazyload',parent);
    if(lazyloadImage.length<1){
        return;
    }
    var max = max|| lazyloadImage.length;
    for(var i=0;i<max;i++){
        var imgId=lazyloadImage[i].id;
        var imageCache=localStorage.getItem(imgId);
        if(imageCache){
            lazyloadImage[i].src=imageCache;
            continue;
        }
        var img = new Image();
        img.index=i;
        img.id=imgId;
        img.crossorigin="anonymous";
        
        img.onload=function(){
            var _this=this;
            var zCvs=$('#'+this.id);
            var domCvs=zCvs[0];
            domCvs.src=this.src;
            zCvs.removeClass('lazyload');
            try{
                var cvs=document.createElement('canvas');
                cvs.style.display='none';
                document.body.appendChild(cvs);
                var rcvs=cvs.getContext('2d');
                cvs.width=140;
                cvs.height=108;
                rcvs.drawImage(this,0,0,140,108);
                setTimeout(function(){
                    var data=cvs.toDataURL();
                    localStorage.setItem(_this.id,data);
                    document.body.removechild(cvs);
                },200);
            }catch(ex){
            }
        }
        img.src=lazyloadImage[i].getAttribute('data-src');
    }
}

</script>
</body>
</html>

【热门文章】
【热门文章】