Skip to content
Advertisement

Overlay of two images with transparency

I’m looking for a solution in Javascript maybe to create a real-time preview of products based on multiple options that a consumer could choose from multiple radiobutton.

Exemple : I have a face.png and a hat.png with transparents parts, and a cap, and when I click on cap, I would like to display the image of the cap + the face and if I click on the buttonradio on hat, I would like to update my preview in real time and keep the face and only change the image of the hat (a png with transparency)

Do you have any idea how I could do this?

Thanks in advance !

Advertisement

Answer

you can use a container div and place face and hat inside of that div then position each other with position absolute

i added a function for changing hats by clicking the thumbnail of hat user will change the src attribute of the actual hat image which we were showing

let hats = [
  "https://m.media-amazon.com/images/I/81B6-uzku8L._UX679_.jpg",
  "https://rukminim1.flixcart.com/image/714/857/jiulk7k0/cap/g/r/v/free-hat-peter-india-original-imaf6gzbhh7pydzy.jpeg?q=50",
  "https://contents.mediadecathlon.com/p982435/31cf29c7f44e13d3f77af7bd205a303c/p982435.jpg"
];
let currentIndex = 0;


document.addEventListener("DOMContentLoaded",()=>{

  let thumpnails = document.querySelector('.thumpnails');
  hats.forEach((hat)=> {
    let img = document.createElement('img');
    img.src = hat;
    img.classList.add('thumpnail');
    thumpnails.append(img);
    
    img.onclick= ()=>{showMe(hat)};
    
  });

})

function showMe(src){
  document.querySelector('.hatImg').src = src;
}

//document.querySelector('#next').addEventListener('click',next)
.pic{
position:relative;
width:200px;
height:300px;
border:1px solid black;
}

.face{
  position: absolute;
  height: 150px;
  width:100px;
  background:red;
  bottom:25px;
  left:50px;
  
}
.hatImg{
  width:180px;
  position:absolute;
  left:10px;
  bottom:100px;
  opacity:0.8;
}

.thumpnail{
  width:50px;
  margin: 0.25rem;
}
<div class="pic">
  <div class="face"></div>
  
  <img class="hatImg" src="https://m.media-amazon.com/images/I/81B6-uzku8L._UX679_.jpg">
</div>
<div class="thumpnails"></div>
Advertisement