canvas移動端常用技巧圖片loading


核心知識點:drawImage

作用:將圖片加載在canvas

html:

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>

js:

<script type="text/javascript">

var c=document.getElementById("myCanvas");
var cxt=c.getContext("2d");
var img=new Image()
img.src="flower.png"
cxt.drawImage(img,0,0);

</script>

移動端圖片loading實例

需求:需要給一個列表中的圖片添加加載效果

html

<section class="productul" id="productul">
     <ul>
         <li>
            <a href="#">
             <div class="triangle-topleft"></div>
             <span class="shuxing" data_url="productinfo.html">專屬</span>
             <div class="leftimages fl"><canvas data-src="images/product/product1.png" ></canvas></div>
             <div class="productcontent fr">
                 <p class="ptitle pl10">標題</p>
                  <p class="pdes pl10">簡介這里簡介這里簡介這里簡介這里簡介這里簡介這里簡介這里簡介介這里簡介</p>
                  <p class="pprice pl10">價格:<span class="green">¥5000</span></p>
             </div>
           </a>
         </li>
     </ul>    
</section>

重點css

img{width:100px;birder:0;}
canvas{width:100px;min-height:100px;background:#fff url("../images/loading.gif") center center no-repeat; background-size:15px auto; }

js

var imglength = $("#productul").find("canvas").length;
            if (imglength > 0) {
                $("#productul").find("canvas").each(function () {
                    var imgSrc = $(this).data("src");
                    var imageObj = new Image();
                    imageObj.canvs = $(this)[0];
                    var cvs = imageObj.canvs.getContext('2d');
                    if (cvs) {
                        imageObj.onload = function () {
                            imageObj.canvs.width = this.width;
                            imageObj.canvs.height = this.height;
                            cvs.drawImage(this, 0, 0);
                            $(imageObj.canvs).css("background-image", "none");
                        }
                        imageObj.src = imgSrc;
                    }
                })
            }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM