Uncover concealed images by adjusting the opacity of the cover image during a mouse movement event

As I was working on a project, I came up with a simple code to adjust the opacity of a cover image in order to reveal a hidden image underneath. The setup involved two canvas elements stacked on top of each other, both measuring 500x500 pixels and containing an image each. What I wanted to achieve was to change the opacity of the cover image based on mouse movement so that the hidden image could gradually become visible. However, manipulating the opacity one pixel at a time using e.layerX/Y coordinates proved to be quite tedious and not very user-friendly.

function change_opacity(e){
  if(checked){
  var imageData=ctx2.getImageData(e.layerX,e.layerY,10,10); 
  for(i=3;i<imageData.data.length;i+=4){
  imageData.data[i]=0;


  }

   ctx2.putImageData(imageData,e.layerX,e.layerY);
   }

}

I am now looking for a way to make the opacity change affect a circular section rather than just individual pixels during every mouse move event. Can someone suggest how I can achieve this?

Link to Canvas1 Image

Link to Canvas2 Image

FULL CODE:

   <html>
    <head>
    <style>
    *{margin:0px;padding:0px;}
    #canvas1{
    position:absolute;
    top:51px;
    left:200px;
    border:1px solid black;
    }
    #canvas2{
    position :absolute;
    top:50px;
    left:200px;
    border:1px solid black;

    }
    </style>
    </head>
    <body>
    <canvas id="canvas1" width="500" height="500"></canvas>
    <canvas id="canvas2" width="500" height="500"></canvas>
    <script>
    function makeit(){
    var checked=false;
    var canvas1=document.getElementById('canvas1');
    var canvas2=document.getElementById('canvas2');
    var ctx1=canvas1.getContext('2d');
    var ctx2=canvas2.getContext('2d');
    var img1=new Image();
    img1.src="car1.jpg";

    img1.onload=function (){
    ctx1.drawImage(img1,0,0);
    }
    var img2=new Image();
    img2.src="car2.jpg";

    img2.onload=function (){
    ctx2.drawImage(img2,0,0);
    }
    canvas2.addEventListener('mousedown',check,false);
    canvas2.addEventListener('mousemove',change_opacity,false);
    canvas2.addEventListener('mouseup',uncheck,false);
    function check(){
    checked=true;
    }
    function uncheck(e){
       checked=false;
    }
function change_opacity(e){
  if(checked){
  var imageData=ctx2.getImageData(e.layerX,e.layerY,10,10); 
  for(i=3;i<imageData.data.length;i+=4){
  imageData.data[i]=0;


  }

   ctx2.putImageData(imageData,e.layerX,e.layerY);
   }

}
    }
    window.onload=makeit;
    </script>
    </body>
    </html>

Answer №1

Your insight is spot on - opting for compositing over getImageData & putImageData can significantly improve performance.

Instead of using those methods, you can utilize compositing to effectively "erase" a top image and reveal a bottom image:

Check out this demonstration: http://jsfiddle.net/m1erickson/sHC6x/

By setting the context.globalCompositeOperation="destination-out", any new drawings will act as an eraser on existing ones. This allows you to erase the top canvas to unveil the image beneath it.

The following code (within mousemove) enables you to use the mouse as an eraser on the top canvas:

topContext.save();
topContext.globalCompositeOperation="destination-out";
topContext.beginPath();
topContext.moveTo(startX,startY);
topContext.lineTo(mouseX,mouseY);
topContext.stroke();

To create a circular eraser that is 10px wide, adjust the context stroke settings like so:

topContext.lineWidth=10;
topContext.lineCap = "round";

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

An error occurred due to a state update being attempted on an unmounted component. The solution is to properly cancel all subscriptions and asynchronous tasks in a

Currently, I am attempting to utilize ListEmptyComponent within a FlatList. If there is no data present, I intend to display ListEmptyComponent={} However, in the Loadingsecond component, I am using useEffect to render when loading is true; if there is s ...

Tips for transferring the id from the url to a php function seamlessly without causing a page refresh

I have a div that includes a button (Book it). When the button is clicked, I want to append the id of the item I clicked on to the current URL. Then, use that id to display a popup box with the details of the clicked item without refreshing the page, as it ...

Unable to utilize angular-local-storage

Here is the code snippet I'm working with: angular.module('MyModule').controller('MyController', ['$scope', '$stateParams','$location', '$http','LocalStorageModule', function($s ...

problem with transmitting information through $.ajax

I'm facing a frustrating issue with the $.ajax()... function in my PHP code. I am unable to retrieve the data sent by the ajax request. <?php if ($_POST){ include 'Bdd_connexion.php'; $filiere = $_POST['filiere']; ...

Excessive delay in executing Javascript loops

While developing an EMI calculator for a hybrid mobile app, I encountered a performance issue. The execution within one of the loops takes too long, resulting in the page becoming unresponsive. Here is my code snippet: var EMICalculator = { basicEMI: fun ...

Route.post() is in need of a callback function, however, it was provided with an [object String

I've been working on developing my own vocabulary app by following and modifying the MDN node/express tutorial. While the MDN tutorial runs smoothly, I'm encountering issues with my version. Below are the errors I'm facing: Error: Route.p ...

What is the best way to create a taskbar using HTML or Javascript?

I'm currently developing an innovative online operating system and I am in need of a functional taskbar for user convenience. The ideal taskbar would resemble the Windows taskbar, located at the bottom of the screen with various applications easily ac ...

Mismatch of data types in Google Visualization

I am working with Google Visualization and receiving Unix Epoch timestamps that I need to convert into an array of strings for use in Google Charts. However, I keep encountering an error: Type mismatch. Value 2017-8-25 16:23:54,2017-8-25 16:11:54,... does ...

Struggling with establishing recognition of a factory within an Angular controller

I am currently facing an issue while trying to transfer data from one controller to another using a factory in Angular Seed. My problem lies in the fact that my factory is not being recognized in the project. Below is my snippet from app.js where I declare ...

Retrieving Data from a Database Using JS and NodeJs: Utilizing AJAX to Access Table Data and Showcase it in a

Currently, I am in the process of working on a project using NodeJS where I need to extract data from a MySQL database through AJAX and then display the retrieved table rows in an HTML table format. However, it seems like I might be encountering an issue ...

The use of jquery UI.js is causing issues with loading select menus dynamically

When attempting to load a dynamically loaded select menu on my page using Ajax/PHP, I encountered an issue where the jquery UI plugin prevented the data from loading. As a result, I was unable to see anything when changing the first select menu. Below is ...

Retrieving data from the database into a DIV using ajax

Here is the code snippet I am using to retrieve values from my database at regular intervals: <script type="text/javascript"> $(document).ready(function(){ var j = jQuery.noConflict(); j(document).ready(function() { j(".refreshMe ...

Launch a PowerPoint presentation in a separate tab on your web browser

If you have a link that leads to a .pdf file, it will open in a new tab like this: <a target="_blank" href="http://somePDF.pdf">Download</a> But what about a Powerpoint file, such as a .ppt? Is there a way to make it open in a new browser tab ...

Dealing with multiple jQuery ajax requests - strategies for managing them

Whenever I click the button quickly while there is jQuery Ajax loading, it seems to get stuck. How can I manage multiple requests being fired at the same time? What is the solution for the following: Cancel/abort all previous requests and only handle th ...

Issue with iframe's size not displaying correctly

<body> <script> document.write("<iframe id='theframe' src='http://www.website.com?testvr=" + testvr + " height='900' width='500'></iframe>"); </script> </body> The iframe is added, but ...

Utilizing JSON data as a variable for handling in a Handlebars view within a Node.js/Express application

I am currently seeking a solution to display a view that includes a variable with data fetched from an API. My technology stack involves express, handlebars, and request. Here is the code for the web server's router: const express = require('ex ...

Error in Stripe.js: Unable to access the property 'stripeToken' because it is undefined

I'm currently in the process of integrating stripe.js into a web application that I'm developing. However, I encountered the following error: Cannot read property 'stripeToken' of undefined Although the client-side is setting the hidd ...

importance of transferring information in URL encoded form

Recently, I started learning about node.js and API development. During a presentation, I was asked a question that caught me off guard. I had created a REST API (similar to a contact catalog) where data was being sent through Postman using URL encoded PO ...

Update the user information quickly

In my Express application, I have implemented several routes and a login function. Each user has a balance associated with their data, which is stored in an 'express-session'. However, when the user refreshes the page, I need the balance to be up ...

Utilizing jQuery with live content to determine dimensions as required

Within my web application, I have a page that dynamically retrieves a view with both HTML and JavaScript. The JavaScript is responsible for rendering a chart into the retrieved view. The problem arises because the chart library I am utilizing (flot) necess ...