2013-03-07 63 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