2014-06-11 45 views

回答

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']); 
+0

,但不能创建图像要么 – user3508453

+0

.toDataURL将致命的,如果要求编码跨域图像失败。也许最好的解决方法是(1)将页面上传到服务器,(2)让服务器将跨域图像下载到自身,(3)使用服务器上的“无头浏览器”加载收到的html&css,(4)将页面保存为图片。 PhantomJS是一个很好的无头浏览器......或者只是使用SnagIt来捕获屏幕:-) – markE

2

< DIV>元素不能使用的drawImage() method.Have画布绘制看看Html2Canvas

示例:

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

赫雷什Fiddle

+0

请注意,html2canvas不会从div中捕获任何跨域图像元素。 – markE

+0

是的,它不会与跨域图像元素......但解决方法是使用代理。 – boomcruiser

+0

http://jsfiddle.net/3qNJB/不工作的帮助! @boomcruiser – user3508453