开发者

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

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

var sources = { darthVader: "darth-vader.jpg", 开发者_如何学C yoda: "yoda.jpg" };

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


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜