实现一个进度条功能

在前端开发过程中,老是会遇到各种各样奇葩的样式。小编也遇到过一个进度条样式的问题。

 思考再三,通过canvas将其绘制出来。步骤如下:

第一步:先绘制出一个小的平行四边行。

// 绘制平行四边形的函数
function drawParallelogram(x, y, width, height,color) {
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + width, y);
ctx.lineTo(x + width - height, y + height);
ctx.lineTo(x - height, y + height);
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
}
第二步:然后只需要循环这个方法,改变其x y的值就可循环n个平行四边行
// 绘制一行多个平行四边形
function drawRowOfParallelograms(totalWidth, width, height,color,otherColor) {
const spacing = 5; // 平行四边形之间的间距
const startX = 20; // 第一个平行四边形的起始X坐标
const startY = 0; // 平行四边形的Y坐标
const num = Math.ceil((totalWidth - startX)/(width + 10));
for (let i = 0; i < num; i++) {
const x = startX + (width + spacing) * i;
drawParallelogram(x, startY, width, height,color);
}
drawLastParallelogram(startX + spacing + (width + spacing) * num,canvas.width,width,height,otherColor)
}
第三步:绘制剩余的部分
function drawLastParallelogram(totalWidth,allWidth,width,height,color){
ctx.beginPath();
ctx.moveTo(totalWidth,0)
ctx.lineTo(allWidth,0);
ctx.lineTo(allWidth - width,height);
ctx.lineTo(totalWidth - height,height);
ctx.closePath()
ctx.fillStyle = color;
ctx.fill();
}
 
调用一下此方法。。由此一个大概的进度条就出现了。
// 在Canvas上绘制一行多个平行四边形
drawRowOfParallelograms(440, 15, 20,'#5E95FF','rgba(94, 149, 255, 0.2)');
完整的代码如下:
<!DOCTYPE html>
<html>
<head>
<title>绘制平行四边形</title>
<style>
canvas {
/* border: 1px solid black; */
}
</style>
</head>
<body>
<canvas id="parallelogramCanvas" width="600" height="20"></canvas>

<script>
// 获取Canvas元素
const canvas = document.getElementById('parallelogramCanvas');
const ctx = canvas.getContext('2d');

// // 设置Canvas的宽度和高度
// canvas.width = 600;
// canvas.height = 100;

// 绘制平行四边形的函数
function drawParallelogram(x, y, width, height,color) {
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x + width, y);
ctx.lineTo(x + width - height, y + height);
ctx.lineTo(x - height, y + height);
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
}
function drawLastParallelogram(totalWidth,allWidth,width,height,color){
ctx.beginPath();
ctx.moveTo(totalWidth,0)
ctx.lineTo(allWidth,0);
ctx.lineTo(allWidth - width,height);
ctx.lineTo(totalWidth - height,height);
ctx.closePath()
ctx.fillStyle = color;
ctx.fill();
}
// 绘制一行多个平行四边形
function drawRowOfParallelograms(totalWidth, width, height,color,otherColor) {
const spacing = 5; // 平行四边形之间的间距
const startX = 20; // 第一个平行四边形的起始X坐标
const startY = 0; // 平行四边形的Y坐标
const num = Math.ceil((totalWidth - startX)/(width + 10));
for (let i = 0; i < num; i++) {
const x = startX + (width + spacing) * i;
drawParallelogram(x, startY, width, height,color);
}
drawLastParallelogram(startX + spacing + (width + spacing) * num,canvas.width,width,height,otherColor)
}

// 在Canvas上绘制一行多个平行四边形
drawRowOfParallelograms(440, 15, 20,'#5E95FF','rgba(94, 149, 255, 0.2)');
</script>
</body>
</html>
 
最终实现的效果:

 

posted @ 2023-07-05 14:58  邓忠集  阅读(101)  评论(0)    收藏  举报