如何使用jquery在画布中更改图像源?

时间:2011-06-19 21:01:42

标签: jquery html5 canvas

以下代码确定HTML5 Canvas中两个图像的来源:

  

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

有没有办法可以使用jquery更改这些图像的来源?

1 个答案:

答案 0 :(得分:5)

我认为@robertc拥有您所追求的目标,或者如果您的图像存储在其他地方并且您想要根据事件更新画布(例如链接/图像点击),您需要执行类似以下操作;

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