user1780729
user1780729

Reputation: 518

On Load event for getImageData

Hello I have this script that checks for transparent pixels and non transparent pixels. Now i made it so the result is coming from 100px by 100px rectangle on mouse over:

var data = ctx.getImageData(100,100, canvas.width, canvas.height).data;

And right now it shows on mouse of over the result of Opague area and Transparent area.

I would like somehow to visualise this rectangle on load with a grid overlaying the image and the oppaque boxes and transparent one to have different colours like oppaque is green transparent is red. I need probably on load function? But how should it look?

enter image description here

I am stuck here and need someone to direct me in the right position

and here is my current progress:

https://jsfiddle.net/kdichev/Lnp3k5re/

Upvotes: 3

Views: 478

Answers (1)

markE
markE

Reputation: 105015

Since you probably want the game console to still show, you can draw your 100x100 boxes with a reduced alpha (globalAlpha).

Here's example code and a Demo:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var boxWidth=100;
var boxHeight=100;
var boxRows=Math.ceil(865/boxHeight);
var boxCols=Math.ceil(1152/boxWidth);
var boxes=new Array(boxRows*boxCols);
for(var i=0;i<boxes.length;i++){boxes[i]=false;}

var img=new Image();
img.onload=start;
img.crossOrigin='anonymous';
img.src="http://i.imgur.com/RrHayx8.png?1";
function start(){

  ctx.drawImage(img,0,0);

  var d=ctx.getImageData(0,0,cw,ch).data;

  for(var i=0;i<d.length;i+=4){
    if(d[i+3]>200){
      var px=parseInt(i/4);
      var pixelY=parseInt(px/cw);
      var pixelX=px-pixelY*cw;
      var boxX=parseInt(pixelX/boxWidth);
      var boxY=parseInt(pixelY/boxHeight); 
      boxes[boxY*boxCols+boxX]=true;
    }
  }

  ctx.globalAlpha=0.25;
  ctx.fillStyle='red';

  for(var i=0;i<boxes.length;i++){
    var y=parseInt(i/boxCols);
    var x=i-y*boxCols;
    if(boxes[i]==true){
      ctx.fillRect(x*boxWidth,y*boxHeight,boxWidth,boxHeight);        
    }
  }

  ctx.globalAlpha=1.00;
  ctx.fillStyle='black';

}
body{ background-color: ivory; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=1152 height=865></canvas>

Upvotes: 1

Related Questions