Giter Site home page Giter Site logo

georapbox / canvas-circular-countdown Goto Github PK

View Code? Open in Web Editor NEW
16.0 3.0 8.0 822 KB

Draw a configurable circular canvas countdown timer.

Home Page: https://georapbox.github.io/canvas-circular-countdown/

License: MIT License

JavaScript 100.00%
html5-canvas progress-bar countdown-timer circularprogressbar

canvas-circular-countdown's Introduction

npm version License: MIT

canvas-circular-countdown

Draw a configurable circular canvas countdown timer.

Check here for a live demo.

NOTE: Depends on window.requestAnimationFrame. If your environment does not support it, you can polyfill.

Install

$ npm install canvas-circular-countdown --save

Usage

The library is exported in UMD, CommonJS, and ESM formats. You can import it the following ways:

Using ESM import statement

import CanvasCircularCountdown from 'canvas-circular-countdown';

Using CommonJS require statement

const CanvasCircularCountdown = require('canvas-circular-countdown').default;

Old school browser global

<script src="https://unpkg.com/canvas-circular-countdown"></script>

API

Instantiation

new CanvasCircularCountdown(element, [options], [onTimerRunning])
Param Type Description
element HTMLElement (Required) The element that the countdown is drawn to. If is a canvas element, the countdown will be drawn on it; otherwise a canvas element will be created and appended to element.
options Object (Optional) Options that can be overriden by user. See below for more details about each option.
onTimerRunning Function (Optional) Function to be executed while timer is running. Parameters passed by include the percentage remaining, an object containing the remaining and elapsed time and the CanvasCircularCountdown instance.

Options

Param Type Default Description
duration Number 60 * 1000 The timer's duration in milliseconds. Throws TypeError if the provided value is not a Number or is NaN.
elapsedTime Number 0 The time that has elapsed in milliseconds. Throws TypeError if the provided value is not a Number or is NaN.
throttle Number undefined Throttle duration in milliseconds. Must be a number lower or equal to the duration option. If provided, it limits the number of times the canvas is drawn in the given period, therefore the number of times the callback function onTimerRunning can be called. You can use it if you perform heavy tasks inside the onTimerRunning callback function to improve performance. Always prefer small numbers, eg. 250, etc
clockwise Boolean false Determines the direction of the progress ring. By default the direction is counterclockwise.
radius Number 150 The radius of the circular countdown in pixels.
progressBarWidth Number 15 The circular progress bar in pixels.
progressBarOffset Number 5 The number of pixels that will be left between the edges of the progress bar and the rest of the circle.
circleBackgroundColor String "#ffffff" The background color of the main circle.
emptyProgressBarBackgroundColor String "#dddddd" The background color of the progress bar when is empty.
filledProgressBarBackgroundColor 1 String|Function "#00bfeb" The background color of the progress bar when is filled.
captionText 1 String|Function undefined The text to be displayed as caption inside the countdown circle. By default if it is left as undefined and showCaption is set to true, the remaining percentage will be displayed.
captionColor 1 String|Function "#343a40" The foreground color of the caption string.
captionFont 1 String|Function "20px sans-serif" The text style of the caption string. Check here for available values.
showCaption 1 Boolean|Function true Whether the caption text inside the countdown circle will be displayed or not.
draw Function undefined A function that exposes CanvasRenderingContext2D to allow free drawing on the canvas element. The function is called with 2 arguments. The first argument is the CanvasRenderingContext2D and the second is an object with information like the canvas width/height, the remaining percentage and an object containing the remaining and elapsed time.

1 If it is a function, the remaining percentage and an object containing the remaining and elapsed time are passed as parameters and it should return the appropriate type for each option. For example, for showCaption should return a boolean (true or false), but for captionColor should return a string. Useful when you need to change some options' values depending on the remaining percentage or the remaining/elapsed time.

Instance methods

start()

Start the timer. If the timer has been already started, the timer will just resume.

start() => CanvasCircularCountdown

stop()

Stop/Pause the timer.

stop() => CanvasCircularCountdown

reset()

Resets the timer to initial specified duration extracting the elapsedTime if provided.

reset() => CanvasCircularCountdown

style(options = {})

Change the styles of the circular countdown at any time while te timer running.

Param Type Default Description
options Object {} Any of the options provided above can be changed apart from the duration, elapsedTime and throttle options.
style(options = {}) => CanvasCircularCountdown

setDuration(time)

Set the timer's duration (in milliseconds), at any time, even when the timer is running.

Param Type Default Description
time Number - The timer's duration in milliseconds. Throws TypeError if the provided value is not a Number or is NaN.
setDuration(time) => CanvasCircularCountdown

setElapsedTime(time)

Set the timer's elapsed time (in milliseconds), at any time, even when the timer is running.

Param Type Default Description
time Number - The timer's elapsed time in milliseconds. Throws TypeError if the provided value is not a Number or is NaN.
setElapsedTime(time) => CanvasCircularCountdown

Examples

Example 1 - Default configuration

Create a new instance of CanvasCircularCountdown with the default configuration and immediately start the countdown timer. Pause the countdown after 5 seconds have passed.

HTML

<canvas id="countdown-canvas"></canvas>

JavaScript

new CanvasCircularCountdown(document.getElementById('countdown-canvas'), (percentage, time, instance) => {
  if (time.elapsed >= 5000) {
    instance.stop();
  }
}).start();

Example 2 - Custom configuration

Same as the above example, but with custom configuration.

HTML

<canvas id="countdown-canvas"></canvas>

JavaScript

new CanvasCircularCountdown(document.getElementById('countdown-canvas'), {
  duration: 30 * 1000,
  radius: 200,
  progressBarWidth: 20,
  progressBarOffset: 0,
  circleBackgroundColor: '#f5f5f5',
  emptyProgressBarBackgroundColor: '#b9c1c7',
  filledProgressBarBackgroundColor: '#17a2b8',
  captionColor: '#6c757d',
  captionFont: '22px serif',
  showCaption: true
}, (percentage, time, instance) => {
  if (time.elapsed >= 5000 ) {
    instance.stop();
  }
}).start();

Example 3 - Change progress bar and caption string color depending on percentage remaining

HTML

<canvas id="countdown-canvas"></canvas>

JavaScript

const pickColorByPercentage = (percentage, time) => {
  switch (true) {
    case percentage >= 75:
      return '#28a745'; // green
    case percentage >= 50 && percentage < 75:
      return '#17a2b8'; // blue
    case percentage >= 25 && percentage < 50:
      return '#ffc107'; // orange
    default:
      return '#dc3545'; // red
  }
}

new CanvasCircularCountdown(document.getElementById('countdown-canvas'), {
  filledProgressBarBackgroundColor: pickColorByPercentage,
  captionColor: pickColorByPercentage
}).start();

Example 4 - Responsive canvas

HTML

<div id="countdown-container">
  <canvas id="countdown-canvas"></canvas>
</div>

CSS

#countdown-container {
  width: 100%;
  max-width: 500px;
}

JavaScript

const containerEl = document.getElementById('countdown-container');
const countdownEl = document.getElementById('countdown-canvas');

const countdown = new CanvasCircularCountdown(countdownEl, {
  radius: containerEl.getBoundingClientRect().width / 2
}).start();

let resizeTimeout;

window.addEventListener('resize', () => {
  clearTimeout(resizeTimeout);

  resizeTimeout = setTimeout(() => {
    countdownEl.style({
      radius: containerEl.getBoundingClientRect().width / 2
    });
  }, 250);

Example 5 - Change caption text depending on percentage

HTML

<canvas id="countdown-canvas"></canvas>

JavaScript

new CanvasCircularCountdown(document.getElementById('countdown-canvas'), {
  captionText: percentage => {
    if (percentage <= 25) {
      return 'Time is running out!';
    }

    return 'There is time. Don\'t worry!';
  }
}).start();

Example 6 - Free draw on canvas element

HTML

<canvas id="countdown-canvas"></canvas>

JavaScript

new CanvasCircularCountdown(document.getElementById('countdown-canvas'), {
  draw: (ctx, opts) => {
    // Draw a in the centre of the canvas element,
    // with radius being 1/4 of the canvas width.
    ctx.save();
    ctx.beginPath();
    ctx.arc(opts.width / 2, opts.height / 2, opts.width / 4, 0, 4 * Math.PI, false);
    ctx.lineWidth = 5;
    ctx.strokeStyle = opts.percentage >= 50 ? '#008000' : '#ff0000'; // change color according to percentage
    ctx.stroke();
    ctx.restore();
  }
}).start();

License

The MIT License (MIT)

canvas-circular-countdown's People

Contributors

alejandrodevs avatar dependabot[bot] avatar georapbox avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

canvas-circular-countdown's Issues

Override time ticking (elapsedTime)

Hey there,
First of all - thanks for making this library and hitting the nail right in the head.

My requirement

A server maintains the duration and elapsed time. I use sockets to sync with it.
Long story short, I have a duration and elapsedTime which is maintained outside of canvas-circular-countdown. I want canvas-circular-countdown to use the elapsedTime which I provide.

Possible ways to solve this

  1. Add another Option called time which contains the remaining time (pass by reference). Use it simply to display. Or...
  2. Expose a method in instance called "setTime". That way we could use setTime whenever the server timer changes.

Open to more solutions.

onTimerRunning don't work when tab is not active

Hello,

as first let me say you have do a nice Script here, i like it ! =)

But i have a little problem, your timer is anymore running when the tab is anymore in focus.
That is a problem then il added a tick-function on onTimerRunning, so when timer is done it will play an alert sound.

But the tab need to be still active to run the tick-function, this is a big problem.
is it a native problem of canvas or on your script?

I would be very much happy if you can help/fix.

Thank you.

Browser is laggy after a longtime the site are open

I would be interested to know if the canvas element can slow down the browser after a certain time?
Especially when multiple timers are running at the same time?

Since I installed the timer plugin, the website becomes very sluggish after a while, so that the scroll bars can no longer be moved back and forth smoothly and the scrolling is also messy.

I can imagine that canvas is responsible for this and is “garbaging” the server.

maybe you have any idea or a solution to clean it up?

Thank you and best regards.

Possibility to configure elapsed time

Hi everyone,

I have a situation where a circular counter is shown to explain the user the time he has to complete a form. If the user suubmit the form and there are some server validation errors, the page is re render and I would like to start the circular countdown again but with the elapsed time instead of creating a countdown with less duration.

As far as I see in the code, there is an easy way to add it as configuration and pass it to the Timer class instead to always assign this._time with 0. What do you think? Would you accept a PR with that?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.