Create Scratch Card using JavaScript & HTML5 Canvas

Create Scratch Card using JavaScript & HTML5 Canvas
Code Snippet:scratch card with canvas
Author: Prototype
Published: January 19, 2024
Last Updated: January 22, 2024
Downloads: 16,624
License: MIT
Edit Code online: View on CodePen
Read More

Yet another code snippet to create a scratch card using JavaScript and HTML5 canvas. This Vanilla JavaScript plugin allows you to hide your coupon code or other winning code that will show on scratch. You can place any number/text behind the scratch area. Users can scratch with a cursor or touch swipe. Moreover, it shows a real-time scratching animation.

How to Create JavaScript Scratch Card

1. First of all create HTML canvas element and other necessary elements like below:

    <div class="card">
    <div class="base">Coupon Code: 123456789</div>
    <canvas id="scratch" width="300" height="60"></canvas>
    </div>

2. After that, style scratch card with CSS.

    .card{
         width: 300px;
         height: 60px;
         position: relative;
         box-shadow: 1px 2px 6px rgba(0, 0, 0, 0.2);
        }    
        
      .base, #scratch {
        cursor: default;
        height: 60px;
        width: 300px;
          position: absolute;
          top: 0;
          left: 0;
          cursor: grabbing;
      }
      .base {
        line-height: 60px;
        text-align: center;
      }
      #scratch {
        -webkit-tap-highlight-color: rgba(0, 0, 0, 0); 
        -webkit-touch-callout: none;
        -webkit-user-select: none;
      }

3. Finally, load the scratch card JS file into your HTML document and done.

<!-- scratch-card-with-canvas JS -->
<script src="js/scratch-card.js"></script>

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

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