互联网技术 · 2024年2月15日

使用HTML代码实现图片逐块加载功能

这篇文章主要介绍了基于HTML代码实现图片碎片化加载功能,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

今天来实现一个图片碎片化加载效果,效果如下:

我们分为 3 个步骤来实现:

定义 html 结构

拆分图片

编写动画函数

定义html结构

这里只需要一个 canvas 元素就可以了。

<html>
  <body>
    <canvas
      id=”myCanvas”
      width=”900″
      height=”600″
      style=”background-color: black;”
    ></canvas>
  </body>
</html>

拆分图片

这个例子中,我们将图片按照 10 行 10 列的网格,拆分成 100 个小碎片,这样就可以对每一个小碎片独立渲染了。

let image = new Image();
image.src =”https://tianxun.xyz/Images/easyvpn24/RwcjZHSb8E.jpg”;

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 :告诉浏览器,你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。

编写动画函数

接下来我们编写动画函数,让浏览器在每一次重绘前,随机渲染某个小碎片。

这里的核心是 context.drawImage 方法。

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://tianxun.xyz/Images/easyvpn24/RwcjZHSb8E.jpg”;

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

   &

OpenMagic API

Need more than content? Move into the product flow.

If you are here for model access, pricing, developer docs, or the future API console, the dedicated product path now lives on api.openmagic.ai.

登录免费注册