2014-10-06 38 views
2

我正在處理一個插件,其中我將圖像轉換爲畫布並存儲爲數據url。該函數觸發'load'事件,但是如何將圖像轉換爲已經在網頁上? (不想刷新頁面或再次加載任何圖像)。我嘗試使用Filereader()函數,但也可用於'onload'概念。那麼當用戶點擊圖像時,如何將圖像保存爲數據url?將圖像轉換爲已加載的畫布

image.addEventListener("load", function() { 

     var imgCanvas = document.createElement("canvas"), 
      imgContext = imgCanvas.getContext("2d"); 
      imgCanvas.width = image.width; 
      imgCanvas.height = image.height; 

      imgContext.drawImage(image, 0, 0, image.width, image.height);  
      imgInfo = imgCanvas.toDataURL("image/png"); 

      localStorage.setItem("imgInfo", imgInfo); 
     }, false); 

回答

5

現在它完美地工作了。如果您使用JavaScript創建臨時圖像元素,然後將其存儲在localStorage中。這對我工作希望它也會幫助其他人

image = document.createElement('img'); 
    document.body.appendChild(image); 
    image.setAttribute('style','display:none'); 
    image.setAttribute('alt','script div'); 
    image.setAttribute("src", path); 

    var imgCanvas = document.createElement("canvas"), 
    imgContext = imgCanvas.getContext("2d"); 

    // Make sure canvas is as big as the picture 
    imgCanvas.width = image.width; 
    imgCanvas.height = image.height; 

    // Draw image into canvas element 
    imgContext.drawImage(image, 0, 0, image.width, image.height); 
    // Save image as a data URL 
    imgInfom = imgCanvas.toDataURL("image/png"); 
    localStorage.setItem("imgInfo",imgInfom); 
    document.body.removeChild(image); 
0

您可以將點擊偵聽器綁定到圖像上並單擊保存數據URL。

var img = document.getElementById("image"); 
img.addEventListener("click",function(){ 
    var c = document.createElement("canvas"); 
    var ctx = c.getContext("2d"); 
    ctx.canvas.width = img.getAttribute("width"); 
    ctx.canvas.height = img.getAttribute("height"); 
    ctx.drawImage(img,0,0); 
    var imgInfo = c.toDataURL("image/png"); 
    localStorage.setItem("imgInfo", imgInfo); 
}); 
+0

我已經試過,它不工作 – 2014-10-06 09:51:19

+0

你得到什麼錯誤?是否說'受污染的畫布可能無法出口'? – Gilsha 2014-10-06 11:43:24

+0

沒有顯示任何錯誤。它只是存儲「數據:」,這就是它,此後沒有字符串 – 2014-10-06 13:25:18