简体   繁体   English

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

[英]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: 以下代码确定HTML5 Canvas中两个图像的来源:

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

Is there a way I can change the source of these images using jquery? 有没有办法可以使用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 (eg a link/image click) you would need to do something similar to the following; 我认为@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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM