用帆布替换图像不起作用

时间:2013-02-16 13:47:50

标签: javascript jquery html5 html5-canvas image-conversion

我有一个将图像转换为canvas的函数。我尝试使用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);
    }

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

您缺少jQuery选择以将replaceWith应用于您的图片:

替换它:

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/