When the getImageData event is triggered upon loading

Hello, I have a script that identifies transparent and non-transparent pixels. Currently, the result is displayed from a 100px by 100px rectangle on mouseover:

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

During mouseover, it shows results for both opaque and transparent areas.

I want to visualize this rectangle upon loading with a grid overlaying the image. Opaque areas will be green and transparent areas red. Do I need an onload function for this? How should it be implemented?

I am currently stuck and seeking guidance in the right direction.

Check out my progress here:

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

Answer №1

To ensure the game console remains visible, consider drawing your 100x100 boxes with a reduced alpha (globalAlpha).

Check out this example code and 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Continue running the remaining part of the function once the asynchronous function has completed its execution

To obtain the last 4 digits of a payment using Stripe, I need to execute an async function that contains another async function. Once these functions are resolved, I aim to update the database with the last four digits. It is crucial to ensure that the dat ...

Ways to update a component when the state changes

When attempting to access components that require authentication, I want to redirect to the login page if the user is not logged in. However, I am facing an issue with initializing the firebase auth object, as there is a small delay. The documentation sugg ...

Encountered an error when attempting to submit with Node.js and Express.js connected to MySql - "Cannot POST /login

I am currently working on creating a basic login page using node.js with the express.js and mysql packages. The goal is to redirect users to the layout.html page if their username and password exist in the mysql database. For this project, I have set up a ...

Generating a JavaScript bundle using the npm TypeScript compiler

Is there a way to compile TypeScript source files into one JavaScript bundle file? We have developed a tool on node.js and are currently using the following TypeScript compilation code: var ts = require('typescript'); ... var program = ts.creat ...

Navigation isn't aligning correctly on the right side

I am having trouble with my navigation menu not aligning properly to the right. <div class="logo"> <h2><i class="icon-reorder"></i> Frosty</h2> </div> <div class="nav"> <a href="#">Home</a> </div& ...

What steps are involved in using a Python method to create a brand new class object?

I need help with the following issues regarding the code that is not functioning correctly: Is there a way to modify the search method in order for it to return a New Database object? Can the __init__ function accept a schema and a list (which consists o ...

What is the best way to control the amount of rows displayed in my gallery at any given time?

I need help with customizing my gallery that is dynamically generated from a directory using PHP. My goal is to display only 2 rows of 4 images each, totaling 8 images, with a "show more" button for loading additional rows. How can I set a limit on the n ...

Accessing Struts2 tag attributes with JavaScript

Currently, I am using struts2 with jsp. Within the JSP file, there is a table with several rows of data. To display the row data in the table, iterators are being used. Each row includes a button that allows the user to update the row's data, such as ...

What causes variations in versions displayed by Node.js?

What causes this error to appear when using node version v16.17.1? https://i.sstatic.net/yJdEx.png ERROR: npm is known not to run on Node.js v10.19.0 UP--- I had multiple versions of node installed, with the default being an older version. I was able t ...

Creating an XPATH Selector with SCRAPY

Having trouble retrieving the product name from a webpage: Struggling to locate XPATH that delivers a useful, specific result. Apologies for my initial question being quite basic :( class V12Spider(scrapy.Spider): name = 'v12' start_ur ...

The ng-repeat directive adds an additional line after each iteration of the list item

Whenever the angular directive ng-repeat is utilized with an <li> element, I notice an additional line appearing after each <li>. To demonstrate this issue, see the simple example below along with corresponding images. Here is a basic example ...

Customize the URL path in Next.JS according to the user's location

My Next JS website is hosted on the domain abc.com. I would like the site to automatically detect a visitor's location, retrieve their country code, and then redirect them to abc.com/country_code. ...

Design a dynamic advertisement page using HTML and Bootstrap to ensure responsiveness

I am currently working on a marketing project where I want to give clients the ability to customize their landing page with image ads in a layout that looks something like this: -------------------------------------------------------------------------- | ...

Use jQuery and AJAX to update the current HTML content only when the image has finished loading

I am attempting to load a .php file that contains a 2Mb image into a specific div. While I can make this work with ajax, my issue is that I only want the content of the current div to be replaced with the new one once the image finishes loading. Currently ...

Javascript encountered an error upon attempting to return from the main function

I have a function that calls the database to perform an action: function callQuery(query) { db.query(query, (err, res) => { if (err) { // Error connecting to DB console.log(err.stack) } else { // Return the results ret ...

Start up Angular with a Fire $http.get when the page loads

I am facing an issue where my $http.get() request is firing after the home page has already loaded. How can I ensure that the request fires before the page loads so I can utilize the returned data on the page? Here is a snippet of the routing code: var l ...

Modifying an object's value before pushing it into an array in JavaScript

I've been struggling to find the right keyword to search for my issue. I've spent hours trying to figure out what's wrong, but it seems like a simple case of pushing an object into an array. The problem arises when I try to log the values of ...

What is the best way to implement colorful opening hours in code?

I found this code on a different platform and decided to tweak it to display only Monday - Friday, Saturday, and Sunday. However, I'm stuck trying to update the Javascript code to match my modifications. Any help would be appreciated! You can view th ...

The fluid table within the Bootstrap container is not adapting to different screen

Can't figure out why the bootstrap container fluid table is not responsive. Even though I used an example of My First Bootstrap Page that works fine and is responsive, this particular table remains unresponsive. I want to avoid using a scroll but will ...

Troubleshooting: WordPress failing to launch Bootstrap Modal

I recently transformed my PHP website into a WordPress theme, but unfortunately, I am facing an issue with my Bootstrap modal not opening in WordPress. ***Header.php*** <a id="modal_trigger" href="#modal" class="sign-in-up"><i class="fa fa-user ...