JavaScript Canvas Countdown Timer

JavaScript Canvas Countdown Timer
Code Snippet:canvas countdown timer
Author: Kylo
Published: January 9, 2024
Last Updated: January 22, 2024
Downloads: 1,346
License: MIT
Edit Code online: View on CodePen
Read More

The JavaScript code snippet helps you to create a Canvas based Countdown Timer on a webpage. It uses an HTML canvas element to create a visual representation of the remaining days, hours, minutes, and seconds until a specified date. This timer is helpful for tracking time intervals or creating a sense of urgency on your website.

You can use this code on your website to add a stylish countdown timer. It’s beneficial for creating a sense of urgency, such as for limited-time promotions or event countdowns.

How to Create a Javascript Canvas Countdown Timer

1. First of all, load the Reset CSS by adding the following CDN link into the head tag of your HTML document.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">

2. Create the HTML structure for your countdown timer. You can place it anywhere on your webpage. The code provides four canvas elements for days, hours, minutes, and seconds.

<div class="item-time">
  <div class="card">
    <div class="word">DAYS</div>
    <canvas class="days" width="50" height="50"></canvas>
  </div>
  <div class="card">
    <div class="word">HOUR</div>
    <canvas class="hours" width="50" height="50"></canvas>
  </div>
  <div class="card">
    <div class="word">MIN</div>
    <canvas class="minutes" width="50" height="50"></canvas>
  </div>
  <div class="card">
    <div class="word">SEC</div>
    <canvas class="seconds" width="50" height="50"></canvas>
  </div>
</div>

3. Add styles to your countdown timer using CSS. Customize the appearance to match your website’s design. The following CSS code helps you get started with a dark-themed countdown timer.

body{
 font-family: "Helvetica Neue", "Helvetica", Helvetica, Arial, sans-serif;
  background: #141414;
  display: flex;
  justify-content: center;
}
.item-time {
  display: grid;
  margin-top: 2rem;
  grid-template-columns: repeat(4, 1fr);
  column-gap: .5rem;
}
.word {
  text-align: center;
  font-size: 0.8rem;
  text-shadow: 0 1px 2px #000;
  color: #c1c1c1;
}
.card {
  background: #333;
  color: #ccc;
  padding: 0.5rem;
  border-radius: 0.4rem;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.7);
}

4. Finally, add the following JavaScript code to your project. It divides this time into days, hours, minutes, and seconds, and updates the canvas elements accordingly.

class Countdown {

    /**
     * @param {Date} dateTo
     */
    constructor(itemSelector, dateTo) {
        this.itemSelector = itemSelector;
        let $ = el => document.querySelector(el);
        this.dateSelectors = {
            d: $('.days').getContext('2d'),
            h: $('.hours').getContext('2d'),
            m: $('.minutes').getContext('2d'),
            s: $('.seconds').getContext('2d')
        };
        this.dateTo = dateTo;
        requestAnimationFrame(() => this.set());
    }

    /**
     * Main function
     */
    set() {

        let today = new Date();

        for (let selector in this.dateSelectors) {
            let s = this.dateSelectors[selector];
            this.clear(s);
            this.setTime(s, this.dateDiff(selector, today, this.dateTo));
        }
        requestAnimationFrame(() => this.set());
    }

    /**
     * Clear canvas
     * @param {canvas} ctx 
     */
    clear(ctx) { ctx.clearRect(0, 0, 60, 60); }

    setTime(ctx, until) {
        ctx.font = 'bold 2rem sans-serif';
        ctx.shadowColor = "#000";
        ctx.shadowOffsetX = 0;
        ctx.shadowOffsetY = 1;
        ctx.shadowBlur = 2;
        ctx.fillStyle = "#ccc";
        ctx.textAlign = "center";
        ctx.fillText(until, 25, 40);
    }

    /**
     * 
     * @param {String} datepart  enum {'m',  'd', 'h', 's'}
     * @param {Date} fromdate 
     * @param {Date} todate 
     */
    dateDiff(datepart, fromdate, todate) {
        datepart = datepart.toLowerCase();
        let diff = todate - fromdate;
        let divideBy = {
            d: 86400000,
            h: 3600000,
            m: 60000,
            s: 1000,
            ms: 1
        };

        let modulo = {
            d: 1,
            h: divideBy['d'],
            m: divideBy['h'],
            s: divideBy['m'],
            ms: divideBy['s']
        }

        return Math.floor(diff % modulo[datepart] / divideBy[datepart]);
    }

}

//set tomorrow date
new Countdown('.item-time', new Date(new Date().getTime() + 24 * 60 * 60 * 1000));

That’s all! hopefully, you have successfully created the JavaScript Canvas Countdown Timer on your website. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X