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>