Giter Site home page Giter Site logo

scratchcard's Introduction

Scratchcard-js

Build version

ScratchCard is a js lib to simulate a scratchcard in browser with html5 and canvas.

You can see the demo page.

Install

You can install ScratchCard with npm:

npm install --save scratchcard-js

or just clone this repo:

git clone https://github.com/Masth0/ScratchCard.git

and pick in the folder ./build the file scratchard.min.js

Getting started

import {ScratchCard, SCRATCH_TYPE} from 'scratchcard-js'

const scContainer = document.getElementById('js--sc--container')

// You also can pass HTML Element or a string for querySelector
// new ScratchCard(htmlElement...

const sc = new ScratchCard('#js--sc--container', {
  scratchType: SCRATCH_TYPE.SPRAY,
  containerWidth: scContainer.offsetWidth,
  containerHeight: 300,
  imageForwardSrc: '/images/scratchcard.jpg',
  imageBackgroundSrc: '/images/result.png',
  htmlBackground: '<p class="test"><strong>Hello i am HTML content !</strong></p>',
  clearZoneRadius: 50,
  nPoints: 30,
  pointSize: 4,
  enabledPercentUpdate: true, // True by default
  percentToFinish: 50, // enabledPercentUpdate must to be true (true by default)
  callback: function () {
    alert('Now the window will reload !')
    window.location.reload()
  }
})

// Init
sc.init().then(() => {
  sc.canvas.addEventListener('scratch.move', () => {
    let percent = sc.getPercent().toFixed(2)
    console.log(percent)
  })
}).catch((error) => {
  // image not loaded
  alert(error.message);
});

Events

'scratch.move'

sc.canvas.addEventListener('scratch.move', function() {
  let percent = sc.getPercent();
  console.log(percent);
});

scratchcard's People

Contributors

h-l avatar jonaswebdev avatar khushbuthakur avatar mabstorm avatar marcelozapatta avatar masth0 avatar thomaslebeauabtasty avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

scratchcard's Issues

Foreground image disappears

I recently implemented this library. I have an image in both the foreground and background. When I drag my mouse or finger through, it drags and clears as expected but the moment I'm no longer pressing down, the whole foreground image disappears, even if I've only cleared a portion of the foreground image.

My current code:

    const scContainer = document.getElementById('js--sc--container')
    const sc = new ScratchCard('#js--sc--container', {
        scratchType: SCRATCH_TYPE.LINE,
        containerWidth: scContainer.offsetWidth,
        containerHeight: 300,
        imageForwardSrc: '//foregroundImage.png',
        imageBackgroundSrc: '//backgroundImage.png',
        clearZoneRadius: 20,
        callback: function () {
        }
    })
   // Init
    sc.init().then(() => {
        sc.canvas.addEventListener('scratch.move', () => {
        let percent = sc.getPercent()
            console.log(percent)
        })
    }).catch((error) => {
        // image not loaded
        alert(error.message);
    });

Pre Cleared

How to set Pre cleared when opening page??

click event inside htmlBackground

Hi,

I have tried to add click function inside the html tag but it is not calling the function.....
It is required to copy the code given in scratch card. I have tried in IONIC.

Please check & let me know
Thanks

examples missing percent update

hi,

with the code of the examples no percentage is calculated but the value is not reflected inside sc__infos

<div class="sc__infos">
            <p>0%</p>
 </div>

there is some glue missing

License information

Really a cool script. I would like to use this for a project. Is there any information about which license this script is released under (MIT?)? Can I use the script for commercial projects?

Responsive UX

Hi again :)

I'm with difficulties trying to turn the scratch-off responsive, always that I tried to handle the canvas element, it loses the visibility (hide) and displays the background/image.

I noted that this project demonstration, the Scratch-Off element is small, apparently to don't be necessary to handle the dimensions for responsive. so is it was purposeful?

Do you have the idea of how to handle the canvas keeping it over the background image?

I'm willing to help in the development of this feature, if you guide me I can implement and send the PR to you review :)

Merci

(reading 'appendChild')

Hello, there is no problem when I create the cards 1 time, but when I try to create them the 2nd time, I get this error. Is there any way to destroy or delete previously created cards? I searched the system a bit but I couldn't find a way

scratchcard.min.js:1 Uncaught TypeError: Cannot read properties of null (reading 'appendChild')
at t.value (scratchcard.min.js:1:21987)
at new t (scratchcard.min.js:1:19107)
at Object. (script.js:421:14)
at Function.each (jquery.min.js:2:2777)
at createScratchCards (script.js:415:7)
at Object.success (script.js:235:17)
at c (jquery.min.js:2:27742)
at Object.fireWith [as resolveWith] (jquery.min.js:2:28487)
at l (jquery.min.js:2:78789)
at XMLHttpRequest. (jquery.min.js:2:81117)

some problems with vue

I want to use ScratchCard with Vue, but i find that if ScratchCard is used in vue child route, it can not be scratched
{ path: '/', component: index, children: [ { name: 'intro', path: '/intro', component: intro }, { name: 'question', path: '/question', component: question }, { name: 'result', path: '/result', component: result }, { name: 'cj', path: '/cj', component: cj } ] }

Error when importing { SCRATCH_TYPE, ScratchCard }

I noticed this error Could not find a declaration file for module 'scratchcard-js'. 'directory/node_modules/scratchcard-js/build/scratchcard.min.js' implicitly has an 'any' type.

This happens when trying to import { SCRATCH_TYPE, ScratchCard } from 'scratchcard-js'; in Angular 13, the only workaround I found was to add "noImplicitAny": false in my tsconfig.json file inside the compiler options. Why is this happening? All other libraries work without issues.

Multiple scratch cards on one page

Hey Masth0!

I've run into a problem trying to init two scratchcards on the same page, both of the canvases are added to the first scratchard element.

Do you have any suggestions or solutions to this specific problem?

Thanks a lot,
David

Unnecessary console.log

Please remove the unnecessary console.log on line 128 in the ScratchCard.ts file. Thanks!

Add destroy eventlistener

Hi,

I use multiple sc in same page, and I would like to deactivate the scratch on multiple sc, but is not possible at the moment,

For further version, possible to add a sc.destroy() or sc.deactivate() who let the foreground image but deactivate the scratch ?

Big thank for your work.

brush type line not working

brush type line does not show scratch nor callback. i wanted a line scratch but only spray and brush type working.

Canvas image Foward desapear

Hi.
I'm facing an issue that, when scratching, the canvas suddenly disappear and the scratch.move percent stop to be fired.
Its happening very offeten in this test link: scratch teste link

Can you help me, pls?

Cannot append Canvas in Vanilla JS Setup (WordPress Website)

I'm currently running a vanilla JS setup (WordPress website, importing Babel-Core and ScratchCard.js in order to use this script), and I've currently hit a similar wall to #44 , however unlike their situation I cannot get my scratchcard to load at all. It responds with the error:

Uncaught TypeError: Cannot read properties of null (reading 'appendChild')
    at ScratchCard.generateCanvas (ScratchCard.ts:210:22)
    at new ScratchCard (ScratchCard.ts:60:10)
    at myscript.js

It seems that the offending function is all to do with generating a canvas, not being able to append anything to the canvas. Unsure of why this is creating so much of an issue. I believe I've imported all of my files properly too:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/6.26.3/browser.min.js?ver=11:10:34" id="babel-core-js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/build/scratchcard.min.js?ver=11:10:34" id="scratchcard-js"></script>
<script type="module" src="https://my.site/wp-content/themes/my-theme/js/myscript.js?ver=11:10:34"></script>

The code in myscript.js is the following:

import 'https://cdn.jsdelivr.net/npm/[email protected]/build/scratchcard.js'; 

/* Scratchcard JS */
const scContainer = document.getElementById('js--sc-container');
const sc = new ScratchCard('#js--sc--container', {
    scratchType: SCRATCH_TYPE.CIRCLE,
    containerWidth: scContainer.offsetWidth,
    containerHeight: scContainer.offsetHeight,
    imageForwardSrc: 'https://geek.design/wp-content/uploads/2024/03/gluttony-scratchcard-front.png',
    imageBackgroundSrc: 'https://geek.design/wp-content/uploads/2024/03/gluttony-scratchcard-back.png',
    clearZoneRadius: 50,
    nPoints: 30,
    pointSize: 10,
    callback: function () {
        console.log('Scratch complete!');
    }
});
sc.init().then(() => {
    sc.canvas.addEventListener('scratch.move', function () {
        console.log('Scratch move!');
    });
}).catch((error) => {
    console.error(error);
});

Any and all help is greatly appreciated.

Bug with screen orientation

When I scratch the scratch card and change the screen orientation a few times, it returns to initial state and I can not scratch again

Multiple scratch-cards not possible

Hello and first thank you for developing this custom script.
I really need to use something like this , but I want to get my api data and store the database ids with custom cards that eventually will get scratched. Like a scratch game , when all the cards are not equal and have different ids and values.

Can you somehow make this script generate different html templates with different ids , not only a single scratch card?
Thank you.

Code usage permission

Hello, @Masth0

I'm interested in using and modifying the code to create my own version of this library. However, I noticed there's no license information.

Could you please grant me permission to copy code from this repository for my use and consider adding an MIT License to the current repository for clarity and open-source collaboration?

If you don't want to add an MIT License may I use this license in my repo?

audio not playing when I click on scratchcard

Guys please help...

I'm trying to add a scratching sound effect while scratching but the browser gives policy error:

Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

var scratchsound = document.getElementById("scratching_audio");
$(".scratchcard_wrapper").on("touchmove", function () {
scratchsound.muted = false;
scratchsound.play();
});

I have to click second time and then it plays.

very strange, if I bind the touch or click event to anything other than the scratchcard container - it works instantly! What the problem?

Multiple ScratchCards

Can I have multiple ScratchCards without having to initialize one by one by the id?

Round scratch area on scratch will not match the scratch percentage

When working with ScratchCard.js I noticed that the scratch area is always a square so I decided to try to round the container so the scratch area would be round the issue I faced was that when scratching the round area part of it would not get scratched because the square corner would not be visible do to the way the CSS rounds corners.

Has anyone tried this before? Is it even possible with the way the scratchCard works?

Steps to Reproduce:

  1. Implement the ScratchCard
  2. In the container holding the canvas, apply border-radius and overflow: hidden;
  3. Implement an element below the canvas to display the scratch percentage
  4. Scratch the area until there is nothing left to scratch.

You will notice that the percentage will not match what was scratched while scratching.

html background does not work

It seems that the information on the "HTML background" section of the demo page is "out of sync" with the demo itself. Neither the Javascript nor the HTML layout mentions anything about the HTML background shown in the demo. Moreover, I could not get it to work based on the incomplete information from the Readme on GitHub.

BTW, I did manage to get it to work with the regular image background. Could you please revise and update the information about how to use an HTML background. This is a great js lib and I can foresee many use cases as far as I am concerned! Thank you a bunch!

Promise after init()

This promise didn't resolve and the addEventListener didn't work properly

// Init
sc.init().then(() => {
  sc.canvas.addEventListener('scratch.move', () => {
    let percent = sc.getPercent().toFixed(2)
    console.log(percent)
  })
}).catch((error) => {
  // image not loaded
  alert(error.message);
});

Except if I put the addEventListener alone, out from the promise:

  sc.canvas.addEventListener('scratch.move', () => {
    let percent = sc.getPercent().toFixed(2)
    console.log(percent)
  })

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.