兩行代碼實現圖片碎片化加載

今天來實現一個圖片碎片化加載效果,效果以下:javascript

碎片化加載
碎片化加載

咱們分爲 3 個步驟來實現:html

  • 定義 html 結構
  • 拆分圖片
  • 編寫動畫函數

定義 html 結構

這裏只須要一個 canvas 元素就能夠了。java

<html>
 <body>  <canvas  id="myCanvas"  width="900"  height="600"  style="background-color: black;"  ></canvas>  </body> </html> 複製代碼

拆分圖片

這個例子中,咱們將圖片按照 10 行 10 列的網格,拆分紅 100 個小碎片,這樣就能夠對每個小碎片獨立渲染了。web

let image = new Image();
image.src = "https://cdn.yinhengli.com/canvas-example.jpeg"; let boxWidth, boxHeight; // 拆分紅 10 行,10 列 let rows = 10,  columns = 20,  counter = 0;  image.onload = function () {  // 計算每一行,每一列的寬高  boxWidth = image.width / columns;  boxHeight = image.height / rows;  // 循環渲染  requestAnimationFrame(animate); }; 複製代碼

requestAnimationFrame:告訴瀏覽器,你但願執行一個動畫,而且要求瀏覽器在下次重繪以前調用指定的回調函數更新動畫。canvas

編寫動畫函數

接下來咱們編寫動畫函數,讓瀏覽器在每一次重繪前,隨機渲染某個小碎片。瀏覽器

這裏的核心是 context.drawImage 方法。dom

let canvas = document.getElementById("myCanvas");
let context = canvas.getContext("2d");  function animate() {  // 隨機渲染某個模塊  let x = Math.floor(Math.random() * columns);  let y = Math.floor(Math.random() * rows);  // 核心  context.drawImage(  image,  x * boxWidth, // canvas 中橫座標起始位置  y * boxHeight, // canvas 中縱座標起始位置  boxWidth, // 畫圖的寬度(小碎片圖像的寬)  boxHeight, // 畫圖的高度(小碎片圖像的高)  x * boxWidth, // 從大圖的 x 座標位置開始畫圖  y * boxHeight, // 從大圖的 y 座標位置開始畫圖  boxWidth, // 從大圖的 x 位置開始,畫多寬(小碎片圖像的寬)  boxHeight // 從大圖的 y 位置開始,畫多高(小碎片圖像的高)  );  counter++;  // 若是模塊渲染了 90%,就讓整個圖片顯示出來。  if (counter > columns * rows * 0.9) {  context.drawImage(image, 0, 0);  } else {  requestAnimationFrame(animate);  } } 複製代碼

完整代碼

<html>
 <body>  <canvas  id="myCanvas"  width="900"  height="600"  style="background-color: black;"  ></canvas>  <script>  let image = new Image();  image.src = "https://cdn.yinhengli.com/canvas-example.jpeg";  let canvas = document.getElementById("myCanvas");  let context = canvas.getContext("2d");  let boxWidth, boxHeight;  let rows = 10,  columns = 20,  counter = 0;   image.onload = function () {  boxWidth = image.width / columns;  boxHeight = image.height / rows;  requestAnimationFrame(animate);  };   function animate() {  let x = Math.floor(Math.random() * columns);  let y = Math.floor(Math.random() * rows);  context.drawImage(  image,  x * boxWidth, // 橫座標起始位置  y * boxHeight, // 縱座標起始位置  boxWidth, // 圖像的寬  boxHeight, // 圖像的高  x * boxWidth, // 在畫布上放置圖像的 x 座標位置  y * boxHeight, // 在畫布上放置圖像的 y 座標位置  boxWidth, // 要使用的圖像的寬度  boxHeight // 要使用的圖像的高度  );  counter++;  if (counter > columns * rows * 0.9) {  context.drawImage(image, 0, 0);  } else {  requestAnimationFrame(animate);  }  }  </script>  </body> </html> 複製代碼

總結

經過這個 Demo,咱們使用了 canvasAPI 實現了圖片的碎片加載效果,是否是特別簡單!編輯器

相關文章
相關標籤/搜索