Build an Interactive Scratch Card for Your Website in 3 steps : Free Downloadable Source File and with Step-by-Step Explanation

Introduction:

Scratch cards are a fun and interactive way to engage users, frequently seen in various mobile apps like Google Pay, where users scratch the surface of a virtual card to reveal hidden rewards. This concept taps into the excitement of the unknown, offering a simple yet effective method for user engagement. Whether it’s a discount, cashback, or a special offer, scratch cards create a sense of anticipation that encourages users to interact with your content.

If you’re building a website and want to integrate a similar interactive experience, this tutorial will guide you step-by-step in creating a scratch card using basic HTML, CSS, and JavaScript. By following this tutorial, you can enhance your website’s interactivity, providing users with a rewarding and engaging experience that is sure to capture their attention.

Why Add a Scratch Card to Your Website?

Adding a scratch card feature to your website can serve multiple purposes:

  • User Engagement: Increase interaction with users, keeping them on your site for longer.
  • Promotions and Rewards: Create a platform for offering exclusive deals, rewards, or coupons.
  • Entertainment: It’s a playful element that adds excitement to your website.

The best part? You don’t need advanced coding skills. With just a few lines of HTML, CSS, and JavaScript, you’ll be able to set up a functional scratch card on your website.

What You’ll Learn in This Tutorial

In this tutorial, we’ll walk you through the process of creating a scratch card from scratch in just three simple steps. You’ll learn how to:

  1. Structure the HTML to create the basic layout of the scratch card.
  2. Style the scratch card with CSS to make it visually appealing.
  3. Implement JavaScript functionality to enable the scratch-off effect.

Additionally, we’ll provide a free downloadable source file that includes all the necessary code, so you can implement it on your website quickly.

Step1: HTML For Scratch Card Effect

HTML Code

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Scratch Card Demo</title>
    <link rel="shortcut icon" href="./final upscale.png" type="image/x-icon">
</head>
<body>

    <div id="scratch-card">
        <img src="./reward.png" alt="Hidden Image">
        <canvas></canvas>
    </div>

</body>
</html>

HTML Explanation:

<!DOCTYPE html>: This declaration defines the document type and version of HTML (HTML5 in this case). It helps the browser understand how to render the page.

<html lang="en">: This tag defines the root of the HTML document. The lang="en" attribute specifies that the language of the document is English.

<head>: The <head> tag contains metadata about the webpage such as its title, character set, and links to external resources like stylesheets or icons.

  • <meta charset="UTF-8">: This ensures that the webpage uses the UTF-8 character encoding, which supports a wide variety of characters and symbols.
  • <title>Scratch Card Demo</title>: This sets the title of the webpage, which appears in the browser tab.
  • <link rel="shortcut icon" href="./final upscale.png" type="image/x-icon">: This adds a favicon (a small icon that appears in the browser tab next to the page title). It’s optional, but it can enhance the branding of your page.

<body>: The <body> tag contains the actual content of the page that will be displayed to the user.

  • <div id="scratch-card">: This <div> element is the container that holds the scratch card content. We’ll style and control this in CSS and JavaScript.
  • <img src="./reward.png" alt="Hidden Image">: This image represents the reward or the content that will be revealed after scratching. In this case, it’s an image of your choice, such as a reward or a discount coupon.
  • <canvas></canvas>: The <canvas> element allows you to draw graphics using JavaScript. In this case, we will use it to create the scratch-off effect.

Step 2 : CSS For Scratch Card

CSS Code

CSS
<style>
body {
    font-family: 'Helvetica Neue', Arial, sans-serif;
    background-color: white;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    user-select: none;
}

#scratch-card {
    position: relative;
    width: 370px;
    height: 370px;
    aspect-ratio: square;
    border: 2px solid #ecf0f1;
    box-shadow: 0 5px 15px rgba(0,0,0,0.3);
    background-color: #ecf0f1;
    overflow: hidden;
    border-radius: 15px;
}

#scratch-card img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

#scratch-card canvas {
    position: absolute;
    top: 0;
    left: 0;
}
</style>

CSS Explanation:

body selector: This defines the styles for the entire body of the webpage.

  • font-family: 'Helvetica Neue', Arial, sans-serif;: This sets the font of the page to Helvetica Neue, with Arial and sans-serif as fallback fonts.
  • background-color: white;: The background color of the webpage is set to white.
  • display: flex;: This applies Flexbox to the body, which allows for easy alignment of items.
  • justify-content: center;: This centers the content horizontally in the middle of the screen.
  • align-items: center;: This centers the content vertically in the middle of the screen.
  • height: 100vh;: The body’s height is set to 100% of the viewport height, ensuring the content takes up the full screen.
  • user-select: none;: This prevents the user from accidentally selecting text or images on the page when interacting with the scratch card.

#scratch-card selector: This styles the scratch card container.

  • position: relative;: This allows us to position the elements inside the container (such as the canvas) relative to this div.
  • width: 370px; height: 370px;: The scratch card has a fixed size, ensuring consistency across different devices.
  • aspect-ratio: square;: This maintains a square aspect ratio for the card.
  • border: 2px solid #ecf0f1;: The card has a light gray border.
  • box-shadow: 0 5px 15px rgba(0,0,0,0.3);: This applies a shadow around the card, giving it a 3D effect and making it stand out.
  • background-color: #ecf0f1;: This sets the background color to light gray.
  • overflow: hidden;: This ensures any content inside the container that exceeds the container’s size is hidden.
  • border-radius: 15px;: The corners of the card are rounded, making it look more polished.

#scratch-card img selector: This styles the hidden image.

  • width: 100%; height: 100%;: This makes the image fill the entire container.
  • object-fit: cover;: This ensures the image covers the entire area without stretching or distorting its aspect ratio.

#scratch-card canvas selector: This styles the canvas element.

  • position: absolute;: The canvas is positioned absolutely, meaning it will overlap the image underneath.
  • top: 0; left: 0;: This places the canvas at the top-left corner of the container, making it cover the entire area of the scratch card.

Step 3 : Javascript for Scratch Card Effect

JavaScript Code

JavaScript
<script>
const scratchCard = document.getElementById('scratch-card');
const canvas = scratchCard.querySelector('canvas');
const ctx = canvas.getContext('2d');

// Set canvas dimensions
canvas.width = scratchCard.offsetWidth;
canvas.height = scratchCard.offsetHeight;

// Fill the canvas with a gradient
const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
gradient.addColorStop(0, '#ffa827');
gradient.addColorStop(1, '#ffa827');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);

// Draw text on the canvas
ctx.fillStyle = '#fff';
ctx.font = '24px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('Scratch here', canvas.width / 2, canvas.height / 2);

let isDrawing = false;
let isMouseDown = false;

// Get mouse position relative to the canvas
function getMousePos(e) {
    const rect = canvas.getBoundingClientRect();
    return {
        x: (e.clientX - rect.left) / (rect.right - rect.left) * canvas.width,
        y: (e.clientY - rect.top) / (rect.bottom - rect.top) * canvas.height
    };
}

// Get touch position for touchscreens
function getTouchPos(e) {
    const rect = canvas.getBoundingClientRect();
    const touch = e.touches[0];
    return {
        x: (touch.clientX - rect.left) / (rect.right - rect.left) * canvas.width,
        y: (touch.clientY - rect.top) / (rect.bottom - rect.top) * canvas.height
    };
}

// Mouse and touch event listeners for scratching
canvas.addEventListener('mousedown', function(e) {
    isDrawing = true;
    isMouseDown = true;
    const pos = getMousePos(e);
    scratch(pos.x, pos.y);
});

canvas.addEventListener('mousemove', function(e) {
    if (isDrawing && isMouseDown) {
        const pos = getMousePos(e);
        scratch(pos.x, pos.y);
    }
});

canvas.addEventListener('touchmove', function(e) {
    e.preventDefault();
    if (isDrawing) {
        const pos = getTouchPos(e);
        scratch(pos.x, pos.y);
    }
});

canvas.addEventListener('mouseup', function() {
    isDrawing = false;
    isMouseDown = false;
});

canvas.addEventListener('mouseleave', function() {
    isDrawing = false;
});

canvas.addEventListener('mouseenter', function() {
    if (isMouseDown)

JavaScript Explanation:

1. Canvas Setup

const canvas = document.querySelector('#scratch-card canvas');
const ctx = canvas.getContext('2d');
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
  • canvas: We select the <canvas> element inside the #scratch-card container using document.querySelector().
  • ctx: The getContext('2d') method gets the 2D drawing context on the canvas, which allows us to draw on the canvas.
  • canvas.width and canvas.height: The width and height of the canvas are set to match the container’s size (offsetWidth and offsetHeight). This ensures the canvas covers the entire scratch card area.

2. Creating the Scratch Surface

const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
gradient.addColorStop(0, '#ffa827');
gradient.addColorStop(1, '#ffa827');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
  • Gradient Creation: The createLinearGradient() method creates a gradient color that simulates the scratchable surface.
    • 0, 0, canvas.width, canvas.height: This defines the direction of the gradient (from the top-left corner to the bottom-right).
    • gradient.addColorStop(): We define the colors for the gradient. Here, we’re using the same color #ffa827 at both stops, simulating a simple colored surface.
  • Applying the Gradient: ctx.fillStyle = gradient sets the fill style to our gradient, and ctx.fillRect() draws the gradient on the entire canvas, creating the scratchable surface.

3. Scratch Function

function scratch(x, y) {
ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath();
ctx.arc(x, y, 50, 0, 2 * Math.PI);
ctx.fill();
}
  • scratch(x, y): This function handles the actual scratching effect. It takes two parameters—x and y, which represent the coordinates of the user’s interaction (mouse or touch).
  • ctx.globalCompositeOperation = 'destination-out': This is the key part of the scratch effect. It changes the drawing mode to “destination-out”, which means anything drawn on the canvas will remove (or “scratch out”) parts of the image.
  • ctx.arc(x, y, 50, 0, 2 * Math.PI): The arc() method draws a circular path at the x, y position where the user interacts. The 50 is the radius of the circle, which defines the size of the scratched area.
  • ctx.fill(): This fills the path (the circular scratch area) and removes it from the canvas, revealing the image beneath.

4. Mouse Event Handlers

canvas.addEventListener('mousemove', (e) => {
scratch(e.offsetX, e.offsetY);
});
  • canvas.addEventListener('mousemove'): This adds an event listener to track the mousemove event on the canvas.
  • e.offsetX and e.offsetY: These represent the coordinates of the mouse relative to the canvas. Every time the user moves their mouse over the canvas, the scratch() function is called at the mouse’s position (offsetX, offsetY), creating a scratched area.

5. Touch Event Handlers

canvas.addEventListener('touchmove', (e) => {
const touch = e.touches[0];
const rect = canvas.getBoundingClientRect();
const x = touch.clientX - rect.left;
const y = touch.clientY - rect.top;
scratch(x, y);
});
  • canvas.addEventListener('touchmove'): This adds an event listener for touch events on mobile devices. Similar to mouse movement, we need to track where the user is touching the screen.
  • Getting Touch Position:
    • e.touches[0]: In a touch event, touches is an array of all active touches. We use the first touch point (touches[0]).
    • canvas.getBoundingClientRect(): This method gets the canvas’s position and size relative to the viewport.
    • touch.clientX - rect.left: This calculates the touch point’s x coordinate relative to the canvas by subtracting the canvas’s left position from the touch’s horizontal position.
    • touch.clientY - rect.top: Similarly, this calculates the y coordinate.
  • Calling scratch(): Once the coordinates are calculated, the scratch() function is called to create the scratching effect at the touch point.

Live Preview the hosted website:

Download complete code :

Scratch card

Git Hub link :

Leave a Comment