捕获div并保存为jpeg

时间:2014-06-11 18:11:16

标签: javascript php jquery canvas

#cap是我要捕获的div。 我使用了ctx.drawImage($('#cap').get(0),0,0,640,480);window.open(canvas.getDataURL('image/jpeg'));

得到Type error 以及如何将其发送到php以保存为a.jpeg

更新

http://jsfiddle.net/3qNJB/无效帮助html2canvas is not a function

2 个答案:

答案 0 :(得分:4)

<无法使用 drawImage()方法在画布上绘制DIV> 元素。请查看Html2Canvas

实施例

 html2canvas(document.getElementById('DivToCapture'), {
      onrendered: function(canvas) {
         // document.body.appendChild(canvas);
       window.open(canvas.toDataURL('image/jpeg'));
     }
  });

继承人Fiddle

答案 1 :(得分:0)

不是用javascript打开图像,只需将其发送到服务器,以便PHP可以接收它,将其保存在服务器上,然后将其发送回浏览器。

我在此处找到了DivsToJPG()函数:Convert html div having multiple images to single image using javascript

var DivsToJPG = function( parent ) {
    this.canvasSizeX = 0;
    this.canvasSizeY = 0;
    this.init = function( parent ) {
        this.images = parent.find('img');
        this.setSizes();
        this.createCanvas();
        this.drawImages();
        this.exportJPG();
    }

    this.setSizes = function() {
        for (var i = 0, l = this.images.length; i < l ; i++) {
            var currentImage = this.images.eq(i);
            var posX = currentImage.position().left;
            var width = currentImage.width();
            this.canvasSizeX = this.canvasSizeX > (posX+width) ? this.canvasSizeX : posX + width;
            //console.log(this.canvasSizeX);
            var posY = currentImage.position().top;
            var height = currentImage.height();
            this.canvasSizeY = this.canvasSizeY > (posY+height) ? this.canvasSizeY : posY + height;

         }
    }

    this.createCanvas = function() {
        this.canvas = document.createElement('canvas');
        this.canvas.id     = "exportCanvas";
        this.canvas.width  = this.canvasSizeX;
        this.canvas.height = this.canvasSizeY;
        this.ctx = this.canvas.getContext("2d");
        document.body.appendChild(this.canvas);
    }

    this.drawImages = function() {
        for (var i = 0, l = this.images.length; i < l ; i++) {
            var currentImage = this.images[i];
            var $currentImage = this.images.eq(i);
            this.ctx.drawImage(currentImage, $currentImage.position().left, $currentImage.position().top, $currentImage.width(), $currentImage.height());
        }
    }

    this.exportJPG = function() {
        var dataURL = this.canvas.toDataURL();
        this.img = document.createElement('img');
        this.img.id = "createdImage";
        this.img.src     = dataURL;
        document.body.appendChild(this.img);
    }

    this.init( parent );
}

var divsToJPG = new DivsToJPG($('#cap'));

$.ajax({
  type : "POST",
  url  : "make-image.php",
  data : { 
     imgBase64 : divsToJPG
  }
}).done(function(data) {

});

然后在PHP中

$img = base64_decode($_POST['imgBase64']);