Is the canvas empty?

I'm trying to make a scratch card using canvas with JS. my question is: can I know if the user have "erased" all the canvas?

I have two images one on top the other, and I managed to make the user "erase" the on-top canvas image. I want to fire up a function when the canvas is empty\completly erased.


var offsetT;
var offsetL;

    var canvas = document.createElement('canvas'); = "canvas";

    var canvasWidth = 290;
    var canvasheight = 269;

    canvas.width = canvasWidth;
    canvas.height = canvasheight;

    var context = canvas.getContext("2d");
    var scratcher = document.getElementById("scratcher");

    var radius = 20;  //Brush Radius


    // set image as pattern for fillStyle
    context.globalCompositeOperation = 'destination-out';
    context.fillStyle = context.createPattern(scratcher, "repeat");

    // for demo only, reveals image while mousing over canvas
    canvas.onmousemove = function (e) {
        var r = this.getBoundingClientRect(),
            x = e.clientX - r.left,
            y = e.clientY -;

        context.moveTo(x + radius, y);
        context.arc(x, y, radius, 0, 2 * Math.PI);

    document.addEventListener('touchmove', function(e){

        var touchobj = e.changedTouches[0]; // reference first touch point (ie: first finger)
        var x = touchobj.clientX;
        var y = touchobj.clientY;

        offsetT = canvas.offsetTop;
        offsetL = canvas.offsetLeft;

        context.moveTo(x-offsetL + radius, y-offsetT);
        context.arc(x-offsetL,y-offsetT, radius, 0, 2 * Math.PI);

        var cursor = document.getElementById('cursor'); = 'block'; = x+ "px"; = y+ "px";
    }, false);


The only way is to check the imageData of the canvas :

var data = ctx.getImageData(0,0,ctx.canvas.width, ctx.canvas.height).data;
var isEmpty = !, function(p){return p>0;});

var ctx = c.getContext('2d');

var isEmpty = function(ctx){
  var data = ctx.getImageData(0,0,ctx.canvas.width, ctx.canvas.height).data;
  return !, function(p){return p>0;});
//first check before drawing
log.innerHTML += isEmpty(ctx)+' ';

//no more empty

// recheck
log.innerHTML += isEmpty(ctx);

we could also have used a for loop : 

//in Function
for(var i=0; i<data.length; i++){
    return false;
  return true;
<canvas id="c"></canvas>
<p id="log"></p>

Need Your Help

Customizing UIButton

iphone ios colors uibutton

I have seen in the in-built apps for iphone that there is a red delete UIButton. My question is, how do I change the color of the button. Usually there is a 'tint' attribute in the attributes inspe...

playing sound files in resources folder

objective-c iphone

I have some mp3 files in my resources folder, how can i play those mp3 files? I just know their name.