Skip to content Skip to sidebar Skip to footer

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 t

Solution 1:

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 = !Array.prototype.some.call(data, 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 !Array.prototype.some.call(data, function(p){return p>0;});
  }
//first check before drawing
log.innerHTML += isEmpty(ctx)+' ';

//no more empty
ctx.fillRect(0,0,10,10);

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

/*
we could also have used a for loop : 

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

Post a Comment for "Is The Canvas Empty?"