2014-06-11 85 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