2

我有一个将图像转换为画布的函数。我尝试使用 jquery 将函数内部创建的画布替换为相关图像,.replaceWith()但它不起作用。

JS:

    imgArray = $("img");
    for (var i = 0; i < imgArray.length; i++)
    {
        convertImageToCanvas(imgArray[i]);
    }

    function convertImageToCanvas(image) {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        canvas.getContext("2d").drawImage(image, 0, 0);
        image.replaceWith(canvas);
    }
4

2 回答 2

1

我很确定这不是您上一个问题中的示例是如何做到的!

以下与您的演示类似,但不完全... http://jsfiddle.net/fsjv7/1/

HTML

<html>
  <head>
    <title>Example</title>
  </head>
  <body>
    <canvas id="example" style="border: 1px solid black" height="10" width="10"></canvas>
    <br />
    Don't place img tags into your document. Place Empty Canvas Tags (with unique names)
  </body>
</html>

Javascript

// add items to this array to load more images into different canvas'
var resources = [ 
  { 
    "destination": "example", 
    "src": "https://developer.mozilla.org/samples/canvas-tutorial/images/rhino.jpg" 
  } 
];

var loadResources = function(obj) {
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      img = new Image();
      img.src = obj[key].src;
      img.onload = (function() {
      var o = obj[key].destination;
        return function() {
          canvas = document.getElementById(o);
          canvas.height = img.height;
          canvas.width = img.width;
          canvas.getContext("2d").drawImage(img, 0, 0);
        }
      })();
    }            
  }
}

window.onload = loadResources(resources);
于 2013-02-16T13:59:27.883 回答
1

您缺少要应用于replaceWith您的图像的 jQuery 选择:

替换这个:

image.replaceWith(canvas); // image here is a DOM object, not a jQuery one

有了这个:

$(image).replaceWith(canvas); // here we select the image with jQuery, making it a jQuery object

http://jsfiddle.net/GHKKq/

于 2013-02-16T15:44:52.047 回答