2013-03-07 21 views
0

我有一個人們可以塗鴉的畫布。我製作了一個按鈕,將每個圖形提交到我的目錄中的一個文件,名爲「images」,該文件位於主文件「Espace Utopique」中。每個文件都有一個不同的名稱「monimage_」time()。所有這一切都很完美,圖像以png格式發送到我的文件夾,我可以閱讀它們。用AJAX將本地文件的隨機圖像上傳到html5畫布

當我打開窗口時,我遇到的麻煩是將這些隨機圖像之一插入到畫布中。這個想法是人們從別人的圖紙中提煉出來的。我發現,我已經保存在名爲「retrieve.php」一個PHP文件中的PHP代碼:

<?php 
$imagesDir = 'Espace Utopique/images'; 

$images = glob($imagesDir . '*.{png}', GLOB_BRACE); 

$randomImage = $images[array_rand($images)]; 
if($res) { 
     echo "ok"; 
    } 
     else {echo "ko";} 
?> 

我發現它可以讓我把圖像轉換成一個HTML5畫布碼:如。

<script> 
window.onload = function() { 
var canvas=document.getElementById("drawing"); // grabs the canvas element 
var context=canvas.getContext("2d"); // returns the 2d context object 
var img=new Image() //creates a variable for a new image 

img.src= "images/vft.jpg" // specifies the location of the image 
context.drawImage(img,20,20); // draws the image at the specified x and y location 
} 
</script> 

我有麻煩的是把兩者放在一起。我試圖把這個AJAX代碼的某個地方,但似乎沒有奏效:

$.ajax({ 


    type: "POST", 
    url: "retrieve.php", 


}).done(function(msg) { 
    alert(msg); 


}); 

} 

有人請幫我請:)我必須失去了一些東西真的很明顯的和愚蠢的。 謝謝!

+0

你應該呼應圖像的URL retrieve.php(不正常或什麼)並在$'.ajax.done'函數中使用這個結果(也就是'$ res'是什麼?) – AmazingDreams 2013-03-07 11:14:13

+0

$ res是結果,這是我用來讓我知道它是否正常工作的結果。 「如果結果達到了,回顯OK,如果沒有,回顯KO」。這只是爲我:) – 2013-03-07 11:32:40

回答

0

像這樣的事情應該工作,這兩個功能相結合;)

<script> 
window.onload = function() { 
    $.ajax({ 
     type: "POST", 
     url: "retrieve.php", 
     succes: function(data) { 
      var canvas=document.getElementById("drawing"); // grabs the canvas element 
      var context=canvas.getContext("2d"); // returns the 2d context object 
      var img = new Image(); //creates a variable for a new image 

      img.src = data; // specifies the location of the image 
      context.drawImage(img,20,20); // draws the image at the specified x and y location 
     } 
    }); 
} 
</script> 

retrieve.php:

$imagesDir = 'Espace Utopique/images'; 

$images = glob($imagesDir . '*.{png}', GLOB_BRACE); 

$randomImage = $images[array_rand($images, 1)]; 
if($randomImage) { 
    echo $randomImage; 
} 
else {echo "path/to/default/image";} //in case $randomimage fails 
+0

非常感謝您的答案,由於某種原因,它不工作。我沒有得到任何圖像的畫布。 – 2013-03-07 12:14:52

+0

存儲在'$ randomImage'中的內容以及存儲在'data'中的內容。即。你直接訪問'retrieve.php'時看到了什麼? – AmazingDreams 2013-03-07 12:51:59

+0

我已經更新了腳本,應該以這種方式工作。 – AmazingDreams 2013-03-07 12:55:01

相關問題