日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

html循环加载多个图片,两行代码实现图片碎片化加载

發布時間:2023/12/10 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 html循环加载多个图片,两行代码实现图片碎片化加载 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

我們分為 3 個步驟來實現:

定義 html 結構

拆分圖片

編寫動畫函數

定義 html 結構

這里只需要一個 canvas 元素就可以了。

id="myCanvas"

width="900"

height="600"

style="background-color: black;"

>

拆分圖片

這個例子中,我們將圖片按照 10 行 10 列的網格,拆分成 100 個小碎片,這樣就可以對每一個小碎片獨立渲染了。

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:告訴瀏覽器,你希望執行一個動畫,并且要求瀏覽器在下次重繪之前調用指定的回調函數更新動畫。

編寫動畫函數

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

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);

}

}

完整代碼

id="myCanvas"

width="900"

height="600"

style="background-color: black;"

>

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);

}

}

總結

通過這個 Demo,我們使用了 canvasAPI 實現了圖片的碎片加載效果,是不是特別簡單!

總結

以上是生活随笔為你收集整理的html循环加载多个图片,两行代码实现图片碎片化加载的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。