» » Use HTML5 canvas to creat scratch card effect

 

Use HTML5 canvas to creat scratch card effect

Author: bamboo06 on 31-10-2014, 01:39, views: 10984

22
Few days ago, we introduced one method using html5 to realize scratch card effect. Today we will create scratch card effects using HTML5 canvas too.

HTML
<div id="sceatchable">Wow, you won $1000!</div>


javascript

(function() {
  var global = this;
  function ScratchCard(element, options, ownerDocument) {

    // apply default arguments.
    var defaultOptions = {
      'color': 'gray',
      'radius': 5
    };
    if (options) {
      for (var key in defaultOptions) {
        if (!(key in options)) {
          options[key] = defaultOptions[key];
        }
      }
    } else {
      options = defaultOptions;
    }
    ownerDocument = ownerDocument || global.document;
    
    // canvas validate.
    var canvas = document.createElement('canvas');
    if (typeof canvas.getContext != 'function')
      return console.log('Canvas not supported.');

    // apply canvas offset & size of element
    var rect = element.getBoundingClientRect();
    canvas.width = rect.width || rect.right - rect.left
    canvas.height = rect.height || rect.bottom - rect.top;
    canvas.style.top = rect.top + 'px';
    canvas.style.left = rect.left + 'px';
    canvas.style.position = 'absolute';
    canvas.style.zIndex = +element.style.zIndex + 1;

    // fill the canvas
    var context = canvas.getContext('2d');
    context.fillStyle = options.color;
    context.fillRect(0, 0, canvas.width, canvas.height);
    context.globalCompositeOperation = "destination-out";
    context.strokeStyle = "rgba(0,0,0,1)";

    // add mouse events to canvas
    // TODO: supply touch events
    // TODO: scratch from the outside
    function scratchStart(event) {
      if (event.button != 0) // not left button
        return;

      var x = event.offsetX || event.layerX;
      var y = event.offsetY || event.layerY;

      context.beginPath();
      context.arc(x, y, options.radius, 0, Math.PI * 2);
      context.fill();

      canvas.addEventListener('mousemove', scratchMove);
      document.addEventListener('mouseup', scratchEnd);
    }

    function scratchMove(event) {
      var x = event.offsetX || event.layerX;
      var y = event.offsetY || event.layerY;

      context.beginPath();
      context.arc(x, y, options.radius, 0, Math.PI * 2);
      context.fill();
    }

    function scratchEnd(event) {
      canvas.removeEventListener('mousemove', scratchMove);
      document.removeEventListener('mouseup', scratchEnd);
    }

    canvas.addEventListener('mousedown', scratchStart);

    // disable element interaction
    ['MozUserSelect',
     'msUserSelect',
     'oUserSelect',
     'webkitUserSelect',
     'pointerEvents']
      .filter(function (cssProp) {
        return cssProp in element.style;
      }).forEach(function (cssProp) {
        element.style[cssProp] = 'none';
      });

    // append canvas to body.
    document.body.appendChild(canvas);
  }

  if (typeof module == 'object' && module.exports) {
    // Node.js module
    module.exports = ScratchCard;
  } else if (typeof define == 'function' && (define.amd || define.cmd)) {
    // AMD or CMD module
    define(ScratchCard);
  } else if (typeof jQuery == 'function' && typeof jQuery.extend == 'function') {
    // jQuery plugin
    jQuery.fn.extend({
      'ScratchCard': function (options) {
        return this.each(function (element) {
          ScratchCard(element, options);
        });
      }
    });
  } else if (typeof angular == 'object' && typeof angular.module == 'function') {
    // AngularJS module
    // TODO: modify it to a directive.
    angular.module('ScratchCard', [])
      .value('ScratchCard', ScratchCard);
  } else {
    // Apply to a global variable.
    if (global.ScratchCard) {
      (function (oldScratchCard) {
        ScratchCard.noConflict = function () {
          global.ScratchCard = oldScratchCard;
          return ScratchCard;
        };
      }) (global.ScratchCard);
    }
    global.ScratchCard = ScratchCard;
  }
}).call(this);

Save it to scratchcard.js, and then in the html call it:

  <script src="scratchcard.js"></script>
  <script>ScratchCard(document.getElementById('sceatchable'));</script>

Category: Javascript / HTML5

Dear visitor, you are browsing our website as Guest.
We strongly recommend you to register and login to view hidden contents.
<
  • 0 Comments
  • 0 Articles
3 October 2016 08:33

Emily Kuhn

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
Can someone break this up into html5, css, and js for me so it looks like a codepen?

<
  • 0 Comments
  • 0 Articles
4 October 2017 21:52

Zoren Janer

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
I favor your current article. It can be very good to view anyone explain in words through the cardiovascular along with lucidity for this critical issue might be quickly seen. details watch internet site. Satta Bazar

<
  • 0 Comments
  • 0 Articles
5 October 2017 17:44

vipseo

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
You there, this is really good post here. Thanks for taking the time to post such valuable information. Quality content is what always gets the visitors coming. Citation Flow Blog Comments

<
  • 0 Comments
  • 0 Articles
9 October 2017 21:17

Morgan Taylor

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
Superior webpage together with the good superior equipment together with I’m certainly this will be dramatically practical. Jual Toner Printer

<
  • 0 Comments
  • 0 Articles
12 October 2017 22:36

Bailey Butler

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
This kind of seems totally best. Every one of these little information are manufactured together with lots of backdrop information. I prefer that a whole lot. great tips to fix marriage soon

<
  • 0 Comments
  • 0 Articles
24 October 2017 23:39

Gale Snider

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
Generate far more articles or blog posts within this subject matter you then have a fabulous strategy to help really encourage writters. Dirty Things To Say To Your Boyfriend

<
  • 0 Comments
  • 0 Articles
25 October 2017 23:21

Michel Jhon

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
Snatch answers I also bear such behalf, you can study my outline here: concrete floor staining miami

<
  • 0 Comments
  • 0 Articles
26 October 2017 22:26

Gabby Wright

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
Thanks for your time in the inviting blogging you’ve become authoring. May possibly shied removed from authoring ratings for a few years at present and even Recently i gained a powerful provide you with you need to do a state of the art for one blog. Uber driver requirements

<
  • 0 Comments
  • 0 Articles
8 November 2017 16:37

Yolandawakers

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
Great survey. I'm sure you're getting a great response. Melasma

<
  • 0 Comments
  • 0 Articles
8 November 2017 19:55

seo master

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
I havent any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us. satta matka tips

<
  • 0 Comments
  • 0 Articles
17 November 2017 17:51

seo master

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
I was looking at some of your posts on this website and I conceive this web site is really instructive! Keep putting up.. nd centre

<
  • 0 Comments
  • 0 Articles
20 November 2017 20:30

Yolandawakers

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
Thank you and thank you very much for connecting us with the ELC. We had a very nice evening at the event. Non Destructive Testing

<
  • 0 Comments
  • 0 Articles
23 November 2017 06:18

seo master

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
This is a very good tips especially to those new to blogosphere, brief and accurate information… Thanks for sharing this one. A must read article. chinese food delivery portland

<
  • 0 Comments
  • 0 Articles
25 November 2017 00:47

Igornor Igornor

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
A very awesome blog post. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Bella Collina homes

<
  • 0 Comments
  • 0 Articles
26 November 2017 19:47

Igornor Igornor

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
I was looking at some of your posts on this website and I conceive this web site is really instructive! Keep putting up.. Harvard University Diploma

<
  • 0 Comments
  • 0 Articles
3 December 2017 05:34

jhonnss khan

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
I wanted to thank you for this excellent read!! I definitely loved every little bit of it. I have you bookmarked your site to check out the new stuff you post. holm law group san diego

<
  • 0 Comments
  • 0 Articles
6 December 2017 17:18

ffgdfgf

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
The birth of replica rolex the first quartz watch was around the 1960s. The beginning of uk replica watches the birth of quartz watch, really shocked the watch market. Mechanical watch suffered a similar "catastrophe" catastrophe rolex replica watches, but now we can see in replica watches uk the watch market, the proportion of mechanical watches did not decrease.

<
  • 0 Comments
  • 0 Articles
7 December 2017 22:54

seo master

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
Hello There. I found your blog using msn. This is an extremely well written article. I will be sure to bookmark it and return to read more of your useful information. Thanks for the post. I’ll certainly comeback. stairservice.com

<
  • 0 Comments
  • 0 Articles
11 December 2017 21:35

sohail khatri

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
it was a wonderful chance to visit this kind of site and I am happy to know. thank you so much for giving us a chance to have this opportunity..question voyance gratuite

<
  • 0 Comments
  • 0 Articles
21 December 2017 02:33

sohail khatri

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
Thank you a bunch for sharing this with all of us you actually realize what you are talking about! Bookmarked. Please also seek advice from my site =). We could have a hyperlink change contract between us! non slip tape

Good post but I was wondering if you could write a litte more on this subject? I’d be very thankful if you could elaborate a little bit further. Appreciate it!non slip tape

<
  • 0 Comments
  • 0 Articles
15 January 2018 23:27

Miller

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
There are many dissertation internet sites on-line after you uncover unsurprisingly identified in your website page. compra panda global protection

<
  • 0 Comments
  • 0 Articles
24 January 2018 22:18

LAkx

Reply
  • Group: Guests
  • РRegistered date: --
  • Status:
 
This unique appearances utterly suitable. Each one of modest data are prepared with the help of great number of experience practical knowledge. I'm keen it again very much. Demolizioni edili a savona

Information
Comment on the news site is possible only within (days) days from the date of publication.