使用canvas绘制一个转动线圈

2021-07-08

很久之前学习canvas写的一个小例子,还挺有意思,拿出来复习一下。

HTML

<canvas id=”c1″ width=”150″ height=”150″ data-text=”24,hrs,200″></canvas>

window.onload = function(){
        let oC = document.getElementById(“c1”);
        let gd = oC.getContext(“2d”);
        let timer = null;
        let x=0,y=0;
        let i=0;
        function dtr(d){
            return d*Math.PI/180;
        }
        let str = oC.getAttribute(“data-text”);
        arr = str.split(“,”);
        timer = setInterval(function(){
            i+=2;
            if(i>=arr[2]) clearInterval(timer);
            gd.clearRect(0,0,oC.width,oC.height);
            //线开头半弧效果
            gd.beginPath();
            gd.arc(75,5,5,0,2*Math.PI);
            gd.fillStyle=”#2e99eb”;
            gd.fill();
            //画线
            gd.beginPath();
            gd.arc(75,75,70,-0.5*Math.PI,dtr(i-90));
            gd.strokeStyle=”#2e99eb”;
            gd.lineWidth = 10;
            gd.stroke();
            //线结尾半弧效果
            gd.beginPath();
            x=75+Math.sin(dtr(i))*70;
            y=75-Math.cos(dtr(i))*70;
            gd.arc(x,y,5,0,2*Math.PI);
            gd.fillStyle=”#2e99eb”;
            gd.fill();
        },20)
    }

发表评论

邮箱地址不会被公开。 必填项已用*标注