How can I change the image source within a canvas using jquery?

12,834

I think @robertc has what you are after, alternatively if your images are stored elsewhere and you want to update the canvas based on an event (e.g. a link/image click) you would need to do something similar to the following;

 <canvas id="e" width="177" height="113"></canvas>
 <script src="jquery.js"></script>
 <script>
// This originally sets the canvas up with image.jpg
  var canvas = $("#e")[0]; // only get first one
  var context = canvas.getContext("2d");
  var img = new Image();
  img.src = "image.jpg";
  img.onload = function() {
  context.drawImage(img, 0, 0);
  };
  </script>
  <a id="a">click</a>

   <script>
   $('#a').click(function(){
   var canvas = $('#e')[0];
   canvas.width = canvas.width;//blanks the canvas
   var c = canvas.getContext("2d");
    var img = new Image();
    img.src = 'image2.jpg';
   img.onload = function(){
    c.drawImage(img, 0, 0);
   }
   return false;
  });
  </script>
Share:
12,834
Mohamed Said
Author by

Mohamed Said

Updated on June 23, 2022

Comments

  • Mohamed Said
    Mohamed Said almost 2 years

    The Following code determines the sources of two images within an HTML5 Canvas:

    var sources = { darthVader: "darth-vader.jpg", yoda: "yoda.jpg" };

    Is there a way I can change the source of these images using jquery?