倒计时 canvas 绘制

16 篇文章 0 订阅

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style type="text/css">
        * { margin: 0; padding: 0; }
        .content { width: 200px; height: 200px; margin: 100px auto 0; }
    </style>
</head>
<body>
    <div class="content">
        <canvas class="canvas" id="canvas" width="200" height="200"></canvas>
    </div>
    <script src="count.js"></script>
</body>
</html>

var srcDegree = 0, //初始位置角度
    targetDegree = 360, //结束位置角度
    allTime = 10,//总时间
    valueTime = 10, //默认动态时间 = 总时间
    drawTimeTxt = 10, //绘制时间 = 默认动态时间
    size = 200,//canvas 大小
    borderWidth = 10,//线条宽度
    baseLineColor = '#ddd',//默认圆颜色
    valueLineColor = '#176ee7',//动态圆颜色
    font = '60px Arial', //字体
    fontColor = '#176ee7',//字体颜色
    timer;//计时器

var canvas = document.getElementById('canvas'); //获取id
var ctx = canvas.getContext('2d'); //创建对象

//绘制基础圆
function drawBase(){
    ctx.beginPath();//开始路径
    ctx.lineWidth = borderWidth;//线条宽度
    ctx.strokeStyle = baseLineColor; //设置笔触颜色
    ctx.arc(size/2,size/2,(size-borderWidth)/2,0,2*Math.PI,false);//ctx.arc(x, y, r, start, end, false); x,y为圆的圆心坐标,start为开始角度(弧度),end为结束角度(弧度),false是设置绘制圆以顺时针方向
    ctx.stroke();//绘制完成
}

//绘制动态圆
function drawValue(srcDegree,targetDegree){
    ctx.beginPath();
    ctx.lineWidth = borderWidth;
    ctx.strokeStyle = valueLineColor; 
    ctx.arc(size/2,size/2,(size-borderWidth)/2,degreeToRadian(srcDegree-90),degreeToRadian(targetDegree-90),false);
    ctx.stroke();
}

//处理角度
function degreeToRadian(degree){
    return degree * Math.PI / 180;
}

//绘制文字
function textTime(){
    ctx.font = font;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillStyle = fontColor;
    ctx.fillText(drawTimeTxt,size/2,size/2);
}

//清除画布
function clearAll(){
    ctx.clearRect(0,0,size,size);
}

//进度条
function draw(srcDegree,targetDegree){
    clearAll();
    textTime();
    drawBase();
    drawValue(srcDegree,targetDegree);
}

//进度条动画
function drawFrame(){
    var easing = 360 / allTime /100 ; // 圆环角度/时间
    if(Math.round(srcDegree)>360){
        clearInterval(timer);
        // clearAll();
    }else{      
        draw(Math.round(srcDegree),targetDegree);
        srcDegree += easing;
        valueTime = valueTime - 0.01;
        drawTimeTxt = Math.ceil(valueTime);
    }
}

//执行倒计时
function render(){
    timer = setInterval(drawFrame, 10);   
}
render();

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值