Coder Social home page Coder Social logo

wscratchpad's Introduction

wScratchPad.js

A jQuery plugin to mimic a scratch card or pad behaviour. Allowing you to scratch off an overlay as either a color or image.

Related Plugins

Settings

Available options with notes, the values here are the defaults.

$('#elem').wScratchPad({
  size        : 5,          // The size of the brush/scratch.
  bg          : '#cacaca',  // Background (image path or hex color).
  fg          : '#6699ff',  // Foreground (image path or hex color).
  realtime    : true,       // Calculates percentage in realitime.
  scratchDown : null,       // Set scratchDown callback.
  scratchUp   : null,       // Set scratchUp callback.
  scratchMove : null,       // Set scratcMove callback.
  cursor      : 'crosshair' // Set cursor.
});

Note on realtime, if set to false this will only send percentage calculations to the scratchUp and should be used to increase performance.

Note on bg and fg, these can be eitehr a valid hex color beginning with # otherwise it will default to trying to set an image.

Examples

Include the following files:

<script type="text/javascript" src="./wScratchPad.min.js"></script>

Percent scratched

$("#elem").wScratchPad({
  scratchDown: function(e, percent){ console.log(percent); },
  scratchMove: function(e, percent){ console.log(percent); },
  scratchUp: function(e, percent){ console.log(percent); }
});

Update on the Fly

var sp = $("#elem").wScratchPad();

sp.wScratchPad('size', 5);
sp.wScratchPad('cursor', 'url("./cursors/coin.png") 5 5, default');

// Or directly with element.

$("#elem").wScratchPad('image', './images/winner.png');

Methods

$('#elem').wScratchPad('reset');
$('#elem').wScratchPad('clear');
$('#elem').wScratchPad('enabled', <boolean>);

Resources

License

MIT licensed

Copyright (C) 2011-2012 Websanova http://www.websanova.com

wscratchpad's People

Contributors

grexican avatar kerncheh avatar richardvandermeer avatar smnarnold avatar websanova 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

wscratchpad's Issues

Not working on CSS Scale

By "not working", I mean the area you "scratch" when the ScratchPad is scaled down (or up) is not accurate and does not scratch the correct spot. Do a test by scaling down the canvas element.

For example, if I scratch the center area, the top left corner will scratch instead.

Stop scratching when user clicked out of the scratchable area ?

Well... If you take a look at the demo plugin, you can see that while you are scratching and you go out of the scratchable area and you release the mouse button. Then you put your mouse on the scratchable area and you can still scratch it. Really hope my explanation is clear to you.

Could you tell me how to avoid it please ?

Thank you very much

Poor performance on mobile devices

Since the plugin calculate the Scratch Percentage on touchmove (aka non-stop), the scratch animation lag on mobiles devices. I suggest the Scratch Percentage get updated only on touchend.

Error while writing the image path for fg key

the image path for bg works perfectly fine, however, when I am giving the image path for foreground key (fg), it shows an error on console and also that image doesn't show up on the page. fg works when I write hex code but it's not taking up any image path.

image

Responsive

Hi! How do I make the wScratchpad responsive?

implement in angular

Hi

I'm trying to implement in angular and cordova but not manage to.
Someone to help me?

thx

Console.log not triggering

Hi,

Did someone encounter this error?
Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': the canvas has been tainted by cross-origin data.

Also I tried to have console.log and alert on this function but it does not trigger at all.

$("#wScratchPad").wScratchPad({
width: 210,
height:100,
image: "/path/to/image.jpg"
image2: "/path/to/image2.jpg"
scratchMove: function(e, percent)
{
if(percent > 80)
{
//do something - I add here a console.log(percent) but it was not call from the devTools of chrome.
}
}
});

Hope you could check this.

Thanks!

Retina Support

Any way to implement retina support? Canvas is blurry on retina displays, etc.

I've used this before, but can't seem to get it to work within your code:

// retina conversion
if(window.devicePixelRatio == 2) {
canvas.setAttribute('width', 800);
canvas.setAttribute('height', 160);
ctx.scale(2, 2);
}

clear on percent scratched not working

Could you tell me why the wScratchpad clear on 70% isnt working I have tried it on chrome (:)) and IE10 (####....)
It also isnt working on the demo.

Many thanks

Tim

touch targets

line: 289
event.originalEvent.targetTouches -> event.originalEvent.changedTouches

realtime is slow in mobile and here's my workaround

In desktop, the performance of using realtime and getting percent scratched is fair enough.
But in mobile, it's slow getting percent in realtime.

My workaround is adding a line around 183 line.

        _scratchFunc: function (e, event) {
            e.pageX = Math.floor(e.pageX - this.canvasOffset.left);
            e.pageY = Math.floor(e.pageY - this.canvasOffset.top);

            this['_scratch' + event](e);

            if (this.options.realtime || event === 'Up') {
                if (this.options['scratch' + event]) {
                    this.options['scratch' + event].apply(this, [e, this._scratchPercent()]);
                }
            }
+           this.options['myFunc'].apply(this, [e, event]);
        },

Usage:

            var count = 0;
            $('#elem').wScratchPad({
                size        : 55,          // The size of the brush/scratch.
                bg          : 'images/bonus/0.jpg',  // Background (image path or hex color).
                fg          : 'images/Scraping.jpg',  // Foreground (image path or hex color).
                realtime    : true,       // Calculates percentage in realitime.
                scratchDown : null,
                scratchUp   : null,
                scratchMove : null,
+               myFunc      : function() {
                    count++;
                    if (count > 100) {
                        this.clear();
                    }
                },
                cursor      : 'crosshair' // Set cursor.
            });

`clear` doesn't work on mobile devices

I want to reveal the whole card when 60% of it is scratched off:

$(function() {
  $('[data-role=scratch-off]').wScratchPad({
    size        : 20,          // The size of the brush/scratch.
    bg          : '/assets/score.png',  // Background (image path or hex color).
    fg          : '#6699ff',  // Foreground (image path or hex color).
    realtime    : true,       // Calculates percentage in realitime.
    cursor      : 'pointer', // Set cursor.
    scratchUp : function(e, percent) {
      if (percent > 60) this.clear();
    }
  });
});

On PC, it works as expected. But on my iPad's Chrome and Safari, it just does not clear.
P.S. this.clear() is copied from the demo site.

UPDATE

The direct cause is:

Uncaught TypeError: Cannot read property 'screenX' of undefined
(anonymous function)  @ wScratchPad.js: 312

It seems that event.changedTouches is always undefined, and when the touch event type is touchend, event.originalEvent.targetTouches is a zero-length array.

I monkey patched line from 311 like this:

      if (first) {
        simulatedEvent.initMouseEvent(
          type, true, true, window, 1,
          first.screenX, first.screenY, first.clientX, first.clientY,
          false, false, false, false, 0/*left*/, null
        );
      } else {
        simulatedEvent.initMouseEvent(
          type, true, true, window, 1,
          0, 0, 0, 0,
          false, false, false, false, 0/*left*/, null
        );
      }

      event.target.dispatchEvent(simulatedEvent);

and everything works fine.

image2 option bug

Unable to get image data from canvas because the canvas has been tainted by cross-origin data.
Uncaught Error: SECURITY_ERR: DOM Exception 18

i got this error on chrome 19 when i set the image2 option.
here is my code:

var sp = $("#wScratchPad").wScratchPad({
width : 560,
height : 321,
image : "background.jpg",
image2 : "foreground.jpg",
size : 30,
scratchDown: function(e, percent){$("#count").html(percent)},
scratchMove: function(e, percent){$("#count").html(percent)},
scratchUp: function(e, percent){$("#count").html(percent)}
});

thank you so much btw~

Not working on Android 4.2 , some suggests

there are some bug with canvas when set content.globalCompositeOperation 'destination-out' on android 4.2. browser does not change the view when we arc or move on the canvas with an alpha color. so i have to change the style of the canvas to make browser redraw after scratchDown scratchMove and scratchUp. i hope u can find a good way to fix this bug,thx.

i do like this:
$this.canvas.css('margin-right', 0px or 1px)// change the margin right in 0px and 1px

other, the wScratchPad does not work with zepto, can we make some change to support it.

Error work on mobile devices

wScratchPad.js:318 Uncaught TypeError: Cannot read property 'screenX' of undefined
at HTMLCanvasElement. (wScratchPad.js:318)
at HTMLCanvasElement.dispatch (jquery.1.11.0.min.js:3)
at HTMLCanvasElement.r.handle (jquery.1.11.0.min.js:3)

[enhancement] Add missing bower.json.

Hey, maintainer(s) of websanova/wScratchPad!

We at VersionEye are working hard to keep up the quality of the bower's registry.

We just finished our initial analysis of the quality of the Bower.io registry:

7530 - registered packages, 224 of them doesnt exists anymore;

We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).

Sadly, your library websanova/wScratchPad is one of them.

Can you spare 15 minutes to help us to make Bower better?

Just add a new file bower.json and change attributes.

{
  "name": "websanova/wScratchPad",
  "version": "1.0.0",
  "main": "path/to/main.css",
  "description": "please add it",
  "license": "Eclipse",
  "ignore": [
    ".jshintrc",
    "**/*.txt"
  ],
  "dependencies": {
    "<dependency_name>": "<semantic_version>",
    "<dependency_name>": "<Local_folder>",
    "<dependency_name>": "<package>"
  },
  "devDependencies": {
    "<test-framework-name>": "<version>"
  }
}

Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.

NB! Please validate your bower.json with jsonlint before commiting your updates.

Thank you!

Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!

Add a disable option

I'd like to be able to disable a scratchpad after a timeout. Is there any option I missed ?
If not, that could be a handy feature to add ;-)

Scratching on Mobile Devices

Hi

Great plugin, I've just tried to test it out on my iPhone but found the scratching doesn't really work.

Is there a way to make it work?

ScratchPad + Cordova (PhoneGap) problem

Hello!

Recenlty'ive triet your demo page with Phonegap built for andorid and checked on Nexus 4.

The problem is that the image is not scratched. The percentage is working, but there is no visible changes as I touch around the canvas.

Square box after scratch the image , why this square box coming ?

Hi Team i am getting square box after scratch the image.

<script>
    $('#ScratchMe').wScratchPad({
        size: 75,          // The size of the brush/scratch.
        bg: '#cacaca',
        fg: '#6699ff',  // Foreground (image path or hex color).
    });
</script>
<div class="Pawna-Camp-ForeGround">
    <div id="ScratchMe">
    </div>
</div>
.Pawna-Camp-ForeGround {
    display:flex;
    align-items: center;
    /*background-color: #5a6dcc;*/
    height:100vh;
    background-size:cover;
}
#ScratchMe {
    background-image: url('../img/WinScratchCard/GooglePay4.JPG');
    background-size: cover;
    height: 300px;
    width: 300px;
    border:hidden;
}

image

excanvas and IE8

The scratchpad does not work in IE8 because of the lacking canvas support (nothin new there), but excanvas while replaces the canvas function for other embedded samples, the scratchpad does not seem to use the implementation.

Not working with cross origin images

Chrome throws:

Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.

As a workaround, I tried to load the images as arraybuffers to build a base64 encoded (as described here). It works well, but now Safari throws:

Cross-origin image load denied by Cross-Origin Resource Sharing policy.

The only solution I found is to remove the crossorigin attribute of the $img property of the scratchpad instance. I replaced this:

this.$img = $('<img src=""/>').attr('crossOrigin', '').css({position: 'absolute', width: '100%', height: '100%'});

with this:

this.$img = $('<img src=""/>').css({position: 'absolute', width: '100%', height: '100%'});

Is this attribute ever usefull ? It should at least be configurable.

responsive issue

when scaling the div the scratch becomes offset from the mouse x/y

Clear scratch

Good afternoon,
I want to create a button for self-clear scratch, but I don't get execute the function for this.
You have any idea for use the function clearRect or another that work?
Thanks.

Black line draws after clicking 'Reset'

If I click on the image, drag off, and then click on reset, a black line begins to draw when I bring my cursor back over the image. Everything's fine if I stop 'scratching' while still in the image. But if I drag my cursor off the image and then click reset, it breaks. Clicking again stops the paintbrush effect.

screen shot 2014-07-23 at 7 44 55 pm

not working in iOS 5.1

I've noticed that the scratch pad does not work on Safari or Chrome on a device running iOS 5.1

Seems to work on iOS versions above and below.

When you try to scratch it just highlights the scratchable area and does not scratch anything off.

Also some issues in Android devices, but haven't pin-pointed those yet.

scratchcard automatically duplicated with jquery.mobile-1-0?

Hello,

I tried to implement my scratchcard in a jquery mobile page, but when i integrate <script src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js" type="text/javascript"> in my code, my scratchpad is duplicated.

Any idea about how to fix that?

Z-Index

I'm having an issue when this is placed within a div element with a z-index. It appears to be just for the negative z-index's as the positive seems to be ok. Is this a bug?

EDIT: It actually appears to be caused by an image that lays over the top of the scratch elements. The top image has a transparent window/frame so you can still see the elements behind it.

wScratchPad in Firefox for Android

Hi,

I try to use wScratchPad for a mobile website and the scratching work really good except for Firefox mobile (16.0.2) on Android.

I i touch the pad i can only "draw" a circle. And if i try to move my finger, no line appears.

I have the same problem with WPaint, i cannot draw anything.

Is there a way to use wScratchPad on this browser ?

image overlay : Error: SECURITY_ERR: DOM Exception 18 wScratchPad.js:255

Hi there,

We had an issue, when trying the image overlays on local drive and within a phonegap mobile packaged app.

Unable to get image data from canvas because the canvas has been tainted by cross-origin data. Uncaught Error: SECURITY_ERR: DOM Exception 18 wScratchPad.js:255

Any input or help would be highly appreciated.

Thank you

Capturee

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.