Pregunta

I have a function that converts images to canvas.I tried to replace the created canvas inside the function with the related image using jquery .replaceWith() but it doesn't work.

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);
    }
¿Fue útil?

Solución

You are missing the jQuery selection to apply replaceWith to your image:

Replace this:

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

With this:

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

http://jsfiddle.net/GHKKq/

Otros consejos

I'm pretty sure that is not how the example from your previous question did it!

The following is similar to your demo but not quite...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);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top