javascript - 当我插入一些数字(例如 31,41,51,61)时,倒计时器无法正常工作

标签 javascript countdowntimer

我想使用 JavaScript 显示一个倒计时器。但是,当我插入当前值为 31,41,51,99,61,81 和其他一些数字时,我无法根据插入的当前值获得弧。弧线应显示当前值。随着数字逐渐减少,接近于零,弧线应该继续朝着完成圆圈的方向移动。

我尝试使用 HTML5 Canvas,我几乎接近得到答案,但它抛出了一些错误。

这些字段应具有最大值输入文本字段和当前值文本字段,以及一个单击后应显示 Canvas 元素内的当前值弧的按钮。请帮忙

         <!-- Click event function, works when button is clicked -->
         function clickevent()
         {
         var max=document.getElementById("maxsec").value;
         var curr=document.getElementById("currsec").value;  
         myFunction(max,curr);
         }
         //This is the 
        function myFunction(maxvalue,currentvalue) {
            //alert(maxvalue + ' ' + currentvalue);
            if (currentvalue<=maxvalue)
            { 
            var x =   (2*3.14*currentvalue/maxvalue);
            var c = document.getElementById("myCanvas");
            var ctx = c.getContext("2d");
        ctx.clearRect(0, 0, c.width, c.height);
        ctx.font="15px Georgia";
        ctx.textAlign = "center";     
        ctx.fillText(currentvalue,c.width/2, c.height/2); 
        ctx.beginPath();
        ctx.arc(75, 75, 50, x, 2 * Math.PI);
              // ctx.lineWidth = 10;
              // line color
              ctx.strokeStyle = 'black';
              ctx.stroke();
        }
        if (maxvalue==currentvalue)
        {
        ctx.clearRect(0, 0, c.width, c.height);
        ctx.font="15px Georgia";
        ctx.textAlign = "center";     
        ctx.fillText("Time Up",c.width/2, c.height/2);
        ctx.textAlign="center";
        }
        }
        
<!DOCTYPE html>
        <html>
        <body>
        <div>
        Max Second: <input type="text" id="maxsec" value="300"><br/>
        Current Second: <input type="text" id="currsec" value="150">
        <button onclick="clickevent()">Click me</button>
        <br/>
       //This is the canvas section where the Arc or the curvature will            be displayed.
        <canvas id="myCanvas" width="150" height="150" style="border:1px       solid #d3d3d3;">
        Your browser does not support the HTML5 canvas tag.</canvas>
        </div>
        </body>
        </html>

最佳答案

您将值作为字符串而不是数字传递到函数中,如果更改以下代码行,它可以正常工作!

JS:

var max=parseInt(document.getElementById("maxsec").value);
var curr=parseInt(document.getElementById("currsec").value);  
myFunction(max,curr);

JSFiddle Demo

请将此使用 setTimeout() 函数制作计时器的尝试作为引用并构建您的代码!

JSFiddle Demo

关于javascript - 当我插入一些数字(例如 31,41,51,61)时,倒计时器无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46153836/

相关文章:

java - 将 CountDownTimer 取消功能转换为 RxJava

javascript - 减少脉轮表中列之间的空白

javascript - jQuery 属性选择器变量

java - 检查是否运行倒计时?

javascript - 使用 Socket.io 和 Node.js 进行倒数计时器广播

Angular 2 - 倒数计时器

javascript - 从 div 元素获取 id 并将其显示为警报

javascript - 调用 React 组件以像警报功能一样显示

javascript - 为什么我无法使用 createElement 创建 Canvas 元素?

android - 等待计时器不会在按钮单击时重新启动