用canvas标签显示图像问题

时间:2011-06-20 21:37:56

标签: javascript jquery image canvas

我是jquery的新手,我有一个关于使用画布显示图像的小项目。一切都会很好,但我在尝试显示所有图像时遇到麻烦,我尝试使用.each(函数)或循环但不工作

这是我的麻烦,任何人都可以帮忙吗?感谢

http://jsfiddle.net/NcKfr/6/

<textarea id="textid">blah  blah blah</textarea>



<canvas id="ca1" width="640" height="480"></canvas>

<script>
 $(document.body).find('*').each(function() {
    var tmp = $("textarea").children().remove();
    var text = $("textarea").text();
    text = text.replace(/<li>/g, "").replace(/<\/li>/g, "").replace(/<br \/>/g, "").replace(/\/>/g, "").replace(/<img/g, "").replace(/ /g, "");
    $("textarea").text(text);
    $("textarea").append(tmp);
    });
 </script>


Script code :

$(function(e) {


 var data = $("#textid").val();
  rows = data.split('src="');
  partNum = [];
  var i;
  var len = rows.length;
 var can = document.getElementsByTagName('canvas')[0];
 var ctx = can.getContext('2d');

    $(document).ready(function() {

  for (i = 1; i < len; i++) {
 partNum[i] = rows[i].substr(0,rows[i].indexOf('"'));
 $.getImageData({
            url: partNum[i],
            success: function(image) {

                // Set the canvas width and heigh to the same as the image
                $(can).attr('width', image.width);
                $(can).attr('height', image.height);
                $(can).css({
                    'background-color': 'none',
                    'border-color': '#fff'
                });

                // Draw the image on to the canvas
                ctx.drawImage(image, 0, 0, image.width, image.height);

            },
            error: function(xhr, text_status) {
                // Handle your error here
            }
        });

  }


    });


});


            success: function(image) {
 script = document.createElement('canvas');
var can = document.body.appendChild(script);

如果我在两行中更改代码,我可以显示所有图像但我可以控制它加载表格1到13.任何身体都可以帮我修复它...谢谢

1 个答案:

答案 0 :(得分:1)

这是一个代码,它将在一个画布上绘制图像。

var url = "http://farm4.static.flickr.com/",
    urls = [
      "3002/2758349058_ab6dc9cfdc_z.jpg",
      "2445/5852210343_d21767f18d.jpg"],
    can = $('#canvas').get(0),
    ctx = can.getContext('2d'),
    canH = 0,
    canW = 0,
    h = 0,
    images = [],
    size = urls.length;

// loop via all images
$.each(urls, function (index, img) {
  $.getImageData({
    url: url + img, 
    success: function (image) {
      images.push(image);
      canH += image.height;
      canW = Math.max(canW, image.width);   
      if (images.length === size) {   
        can.width = canW;
        can.height = canH;
        $.each(images, function (i, img) {
          ctx.drawImage(img, 0, h);
          h += img.height;
        });                
      }
    }
  });
});

您还可以查看:http://jsfiddle.net/HcxG3/6/(看起来getImageData背后的服务目前已关闭)。