二手网站怎么做,万网主机网站建设视频,工程与建设,有没有免费查公司的软件今天来实现一个图片碎片化加载效果#xff0c;效果如下#xff1a;我们分为 3 个步骤来实现#xff1a;定义 html 结构拆分图片编写动画函数定义 html 结构这里只需要一个 canvas 元素就可以了。idmyCanvaswidth900height600style效果如下我们分为 3 个步骤来实现定义 html 结构拆分图片编写动画函数定义 html 结构这里只需要一个 canvas 元素就可以了。idmyCanvaswidth900height600stylebackground-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);}}完整代码idmyCanvaswidth900height600stylebackground-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 实现了图片的碎片加载效果是不是特别简单