Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
           CodeHim.com

Free Web Design Code & Scripts

       
  • Home
  • Code Snippets
    • Accordion
    • Creative
    • Carousel
    • Date & Time
    • Gallery
    • LightBox
    • Menu & Nav
    • Modal
    • Others
    • Portfolio
    • Social Media
    • Text & Input
    • Video Player
    • Zoom
  • HTML & CSS
  • Bootstrap
  • JavaScript
  • Collections
  • About
  • Contact
  • Buy Me a Coffee

Home / Vanilla JavaScript / Speedometer Code in JavaScript

Speedometer Code in JavaScript

January 22, 2024January 11, 2024 by Asif Mughal
Speedometer Code in JavaScript
Share This:
Code Snippet:Tesla speedometer
Author: Tameem Imamdad
Published: January 11, 2024
Last Updated: January 22, 2024
Downloads: 11,165
License: MIT
Edit Code online: View on CodePen
Read More
 Demo
Download (File path is not allowed!)

This JavaScript code snippet helps you to create an animated speedometer to indicate speed. The speedometer display speed in both analog and digital format. The interface is inspired by the Tesla speedometer that is built with HTML5 canvas and JavaScript. You can set a custom speed and change the size of the speedometer according to your needs.

How to Create Speedometer in JavaScript

1. First of all, create a canvas element with an id “canvas” and place it where you want to display the speedometer.

  <canvas id="canvas"></canvas>

2. After that, define the CSS styles for the canvas element as follows:

canvas {
  margin: 0 auto;
  display: block;
}

3. Finally, add the following JavaScript code and done.

'use strict';
/*
* TESLA HUD BY Tameem Imamdad [email protected]
GitHub: https://github.com/tameemi/tesla-speedometer
*/

let dev = false;
//let t0 = 0;
//let t1 = 0;

     var c = document.getElementById("canvas");
        c.width = 500;
        c.height = 500;

        var ctx = c.getContext("2d");

        //Rescale the size
        ctx.scale(1,1);

        var speedGradient = ctx.createLinearGradient(0, 500, 0, 0);
        speedGradient.addColorStop(0, '#00b8fe');
        speedGradient.addColorStop(1, '#41dcf4');

        var rpmGradient = ctx.createLinearGradient(0, 500, 0, 0);
        rpmGradient.addColorStop(0, '#f7b733');
        rpmGradient.addColorStop(1, '#fc4a1a');
        //rpmGradient.addColorStop(1, '#EF4836');

        function speedNeedle(rotation) {
            ctx.lineWidth = 2;

            ctx.save();
            ctx.translate(250, 250);
            ctx.rotate(rotation);
            ctx.strokeRect(-130 / 2 + 170, -1 / 2, 135, 1);
            ctx.restore();

            rotation += Math.PI / 180;
        }

        function rpmNeedle(rotation) {
            ctx.lineWidth = 2;

            ctx.save();
            ctx.translate(250, 250);
            ctx.rotate(rotation);
            ctx.strokeRect(-130 / 2 + 170, -1 / 2, 135, 1);
            ctx.restore();

            rotation += Math.PI / 180;
        }

        function drawMiniNeedle(rotation, width, speed) {
            ctx.lineWidth = width;

            ctx.save();
            ctx.translate(250, 250);
            ctx.rotate(rotation);
            ctx.strokeStyle = "#333";
            ctx.fillStyle = "#333";
            ctx.strokeRect(-20 / 2 + 220, -1 / 2, 20, 1);
            ctx.restore();

            let x = (250 + 180 * Math.cos(rotation));
            let y = (250 + 180 * Math.sin(rotation));

            ctx.font = "700 20px Open Sans";
            ctx.fillText(speed, x, y);

            rotation += Math.PI / 180;
        }

        function calculateSpeedAngle(x, a, b) {
            let degree = (a - b) * (x) + b;
            let radian = (degree * Math.PI) / 180;
            return radian <= 1.45 ? radian : 1.45;
        }

        function calculateRPMAngel(x, a, b) {
            let degree = (a - b) * (x) + b;
            let radian = (degree * Math.PI) / 180;
            return radian >= -0.46153862656807704 ? radian : -0.46153862656807704;
        }

        function drawSpeedo(speed, gear, rpm, topSpeed) {
            if (speed == undefined) {
                return false;
            } else {
                speed = Math.floor(speed);
                rpm = rpm * 10;
            }

            ctx.clearRect(0, 0, 500, 500);

            ctx.beginPath();
            ctx.fillStyle = 'rgba(0, 0, 0, .9)';
            ctx.arc(250, 250, 240, 0, 2 * Math.PI);
            ctx.fill();
            ctx.save()
            ctx.restore();
            ctx.fillStyle = "#FFF";
            ctx.stroke();

            ctx.beginPath();
            ctx.strokeStyle = "#333";
            ctx.lineWidth = 10;
            ctx.arc(250, 250, 100, 0, 2 * Math.PI);
            ctx.stroke();

            ctx.beginPath();
            ctx.lineWidth = 1;
            ctx.arc(250, 250, 240, 0, 2 * Math.PI);
            ctx.stroke();

            ctx.font = "700 70px Open Sans";
            ctx.textAlign = "center";
            ctx.fillText(speed, 250, 220);

            ctx.font = "700 15px Open Sans";
            ctx.fillText("mph", 250, 235);

            if (gear == 0 && speed > 0) {
                ctx.fillStyle = "#999";
                ctx.font = "700 70px Open Sans";
                ctx.fillText('R', 250, 460);

                ctx.fillStyle = "#333";
                ctx.font = "50px Open Sans";
                ctx.fillText('N', 290, 460);
            } else if (gear == 0 && speed == 0) {
                ctx.fillStyle = "#999";
                ctx.font = "700 70px Open Sans";
                ctx.fillText('N', 250, 460);

                ctx.fillStyle = "#333";
                ctx.font = "700 50px Open Sans";
                ctx.fillText('R', 210, 460);

                ctx.font = "700 50px Open Sans";
                ctx.fillText(parseInt(gear) + 1, 290, 460);
            } else if (gear - 1 <= 0) {
                ctx.fillStyle = "#999";
                ctx.font = "700 70px Open Sans";
                ctx.fillText(gear, 250, 460);

                ctx.fillStyle = "#333";
                ctx.font = "50px Open Sans";
                ctx.fillText('R', 210, 460);

                ctx.font = "700 50px Open Sans";
                ctx.fillText(parseInt(gear) + 1, 290, 460);
            } else {
                ctx.font = "700 70px Open Sans";
                ctx.fillStyle = "#999";
                ctx.fillText(gear, 250, 460);

                ctx.font = "700 50px Open Sans";
                ctx.fillStyle = "#333";
                ctx.fillText(gear - 1, 210, 460);
                if (parseInt(gear) + 1 < 7) {
                    ctx.font = "700 50px Open Sans";
                    ctx.fillText(parseInt(gear) + 1, 290, 460);
                }
            }

            ctx.fillStyle = "#FFF";
            for (var i = 10; i <= Math.ceil(topSpeed / 20) * 20; i += 10) {
                console.log();
                drawMiniNeedle(calculateSpeedAngle(i / topSpeed, 83.07888, 34.3775) * Math.PI, i % 20 == 0 ? 3 : 1, i%20 == 0 ? i : '');
                
                if(i<=100) { 
                    drawMiniNeedle(calculateSpeedAngle(i / 47, 0, 22.9183) * Math.PI, i % 20 == 0 ? 3 : 1, i % 20 ==
                    0 ?
                    i / 10 : '');
                }
            }

            ctx.beginPath();
            ctx.strokeStyle = "#41dcf4";
            ctx.lineWidth = 25;
            ctx.shadowBlur = 20;
            ctx.shadowColor = "#00c6ff";

            ctx.strokeStyle = speedGradient;
            ctx.arc(250, 250, 228, .6 * Math.PI, calculateSpeedAngle(speed / topSpeed, 83.07888, 34.3775) * Math.PI);
            ctx.stroke();
            ctx.beginPath();
            ctx.lineWidth = 25;
            ctx.strokeStyle = rpmGradient;
            ctx.shadowBlur = 20;
            ctx.shadowColor = "#f7b733";

            ctx.arc(250, 250, 228, .4 * Math.PI, calculateRPMAngel(rpm / 4.7, 0, 22.9183) * Math.PI, true);
            ctx.stroke();
            ctx.shadowBlur = 0;


            ctx.strokeStyle = '#41dcf4';
            speedNeedle(calculateSpeedAngle(speed / topSpeed, 83.07888, 34.3775) * Math.PI);

            ctx.strokeStyle = rpmGradient;
            rpmNeedle(calculateRPMAngel(rpm / 4.7, 0, 22.9183) * Math.PI);

            ctx.strokeStyle = "#000";
        }


function setSpeed () {
  let speedM = 0;
  let gear = 0;
  let rpm = 0;
   setInterval(function(){
     if (speedM > 160){
        speedM = 0;
        rpm = 0;
      }
     if (speedM > 1 && speedM< 30){
       gear = 1;
     } else if (speedM > 30 && speedM < 50) {
       gear = 2;
          } else if (speedM > 50 &&   speedM < 70) {
       gear = 3;
     } else if (speedM > 70 &&   speedM < 100)      {
       gear = 4;
          } else if (speedM > 100)      {
       gear = 5;
     }
     
     speedM++;
     if (rpm < 1){
      rpm += .03; 
     }
        drawSpeedo(speedM,gear,rpm,160);

   }, 40);
  
}

document.addEventListener('DOMContentLoaded', function() {

    //setInterval(setSpeed, 2000)
    //renderCanvas();
  setSpeed();
    //drawSpeedo(120,4,.8,160);
}, false);

That’s all! hopefully, you have successfully integrated this speedometer code snippet into your project. If you have any questions or facing any issues, feel free to comment below.

Similar Code Snippets:

  • Bus Booking Reservation System using HTML CSS and JavaScript

    Bus Booking Reservation System using HTML CSS and JavaScript

  • Convert Image To Base64 using JavaScript

    Convert Image To Base64 using JavaScript

  • Credit Cart Checkout Form in Vanilla JavaScript

    Credit Cart Checkout Form in Vanilla JavaScript

  • Create Scratch Card using JavaScript & HTML5 Canvas

    Create Scratch Card using JavaScript & HTML5 Canvas

  • Profit & Loss Calculator in JavaScript

    Profit & Loss Calculator in JavaScript

  • Vertical Tabs Using JavaScript

    Vertical Tabs Using JavaScript

  • Parallax Effect Background in JavaScript

    Parallax Effect Background in JavaScript

  • Abacus Calculator in JavaScript

    Abacus Calculator in JavaScript

  • Smooth Scroll to Anchor Vanilla JS

    Smooth Scroll to Anchor Vanilla JS

Asif Mughal

I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.

Categories Vanilla JavaScript
Pure CSS Stylish Dropdown Menu
Simple Tabs in HTML CSS and JavaScript

Leave a Comment Cancel reply

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

  • Categories

    • Accordion 22
    • Bootstrap 81
      • Bootstrap Accordion 1
      • Bootstrap Buttons 4
      • Bootstrap Cards 2
      • Bootstrap Carousel 2
      • Bootstrap Dropdowns 2
      • Bootstrap Forms 6
      • Bootstrap Jumbotron 1
      • Bootstrap Modals 2
      • Bootstrap Navbars 6
      • Bootstrap Panels 1
      • Bootstrap Progress Bars 1
      • Bootstrap Text & Input 3
    • Carousel 58
    • Chart & Graph 15
    • Date & Time 49
    • Gallery 39
    • HTML5 & CSS3 201
    • Layout 17
    • LightBox 19
    • Menu & Nav 95
    • Modal 18
    • Others 58
    • Portfolio 8
    • Social Media 10
    • Text & Input 120
    • Vanilla JavaScript 163
    • Zoom 12

You May Like

Alert (7) Analog Clock (4) Analog Clocks (5) Back to Top (4) Calculator (16) Calendar (5) Chart (3) Color Picker (4) Contact Us Forms (5) Countdown Timer (6) Datepicker (9) Digital Clocks (10) Drag and Drop (4) Dropdown Menu (23) File Uploader (4) Hamburger Menu (9) Horizontal Menu (24) Hover Effects (5) HTML5 Canvas (8) Image Sliders (40) Mega Menu (11) Modal (5) Multi-Level Menu (9) News Ticker (4) Notification (9) Off-Canvas Menu (10) Pagination (5) Parallax (8) Popup Lightbox (20) Progress Bar (5) Range Sliders (4) Scrolling Effects (28) Search Box (4) Select Dropdown (4) Shopping Cart (3) Side Menu (16) Slideshow (19) Social Share Buttons (3) Tabs (9) Text (11) Timeline (5) Timer (4) Tooltip (4) Typing Effect (6) Vertical Menu (14)

Latest Code Snippets

  • Common Open Source Security Vulnerabilities and How to Mitigate ThemCommon Open Source Security Vulnerabilities and How to Mitigate Them
    October 12, 2024
  • Animating Grid-column on Hover Using CSSAnimating Grid-column on Hover Using CSS
    April 1, 2024
  • Star Trails Animation On Mousemove in JavaScriptStar Trails Animation On Mousemove in JavaScript
    March 31, 2024
  • Gravity Button Using Pure CSSGravity Button Using Pure CSS
    March 31, 2024
  • Padlock Toggle Switch in CSSPadlock Toggle Switch in CSS
    March 31, 2024
  • Scroll-driven Animations in Pure CSSScroll-driven Animations in Pure CSS
    March 31, 2024
  • Interactive Notification Center UI in Vanilla JSInteractive Notification Center UI in Vanilla JS
    March 31, 2024
  • Emoji Spinner in Vanilla JavaScriptEmoji Spinner in Vanilla JavaScript
    March 31, 2024
  • Reveal Secret Code Using CSSReveal Secret Code Using CSS
    March 31, 2024
  • Toggle Button in CSS With Stretchable Elastic EffectToggle Button in CSS With Stretchable Elastic Effect
    March 31, 2024

Popular

  • 65+ Login Page in HTML with CSS Code Sample Simple to Difficult - 947,415 views
  • 25+ Best JavaScript Shopping Cart Examples with Demo - 211,945 views
  • Bootstrap Multiselect Dropdown with Checkboxes - 150,952 views
  • Bootstrap 5 Buttons with Icon and Text Tutorial & Demo - 112,364 views
  • 19+ Bootstrap Select Dropdown with Search Box Tutorial & Examples - 101,049 views
  • Bootstrap 5 Sidebar Menu with Submenu Collapse/Hover Tutorial Demo - 88,107 views
  • 19+ Bootstrap 5 Mega Menu Responsive/Drop Down Examples - 86,397 views
  • 99+ Social Media Buttons HTML Code Sample & Tutorial - 86,393 views
  • Bootstrap 4 Modal Popup Login Form Tutorial & Demo - 82,150 views
  • Bootstrap Vertical Menu with Submenu on Click - 80,202 views

Advertisement

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...

CodeHim
  • About
  • Contact Us
  • Terms and Conditions
  • Privacy Policy
Top Categories
  • Bootstrap Snippets
  • JavaScript Snippets
  • HTML CSS Snippets
  • Menu & Nav Snippets
Get in Touch

Follow us on social media to be updated with latest web design code & scripts...

All Rights Reserved © 2026 - CodeHim Inc

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

F5
X