Abhijit Dutta Abhijit Dutta - 1 month ago 9
Javascript Question

Onclick change image

<div class="thumbimg">
<ul class="list-unstyled">
<li class="timgare"><img src="images/F.png" class="dummy_data" id="vader"></li>
<li class="timgare"><img src="images/L.png" class="dummy_data" id="c3po"></li>
<li class="timgare"><img src="images/R.png" class="dummy_data" id="annakin"></li>
<li class="timgare"><img src="images/B.png" class="dummy_data" id="bhdhs"></li>
</ul>
</div>
<canvas id="c" style="border:1px solid black;"></canvas>


Here is my code. How will I change image by using onclick. I'm using the big thumbnail image as a canvas. I'm new in canvas so let me know how will I do that work.

Answer

Please check below working snippet.

$(".timgare").on("click",function(){
  var imgsrc = ($(this).find("img"));
  draw(imgsrc);
  return false;
});
function draw(image){
  var canvas = $('#c')[0];
  canvas.width = 800;
  canvas.height = 800;
  var c = canvas.getContext("2d");
  var img = new Image();
  img.src = image.attr("src");
  img.onload = function(){
    c.drawImage(img, 0, 0);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="thumbimg">
  <ul class="list-unstyled">
    <li class="timgare"><img width="100" src="http://www.planwallpaper.com/static/images/desktop-year-of-the-tiger-images-wallpaper.jpg" class="dummy_data" id="vader"></li>
    <li class="timgare"><img width="100" src="http://www.1zoom.net/big2/61/263820-Sepik.jpg" class="dummy_data" id="annakin"></li>
  </ul> 
</div>
<canvas id="c" style="border:1px solid black;"></canvas>

Comments