0

我有一块画布,人们可以在上面涂鸦。我制作了一个按钮,可以将每个绘图提交到我的目录中名为“images”的文件中,该文件位于主文件“Espace Utopique”中。每个文件都有不同的名称“monimage_”time()。所有这一切都完美无缺,图像以 png 格式发送到我的文件夹,我可以阅读它们。

我遇到的麻烦是在窗口打开时将这些随机图像之一插入到我的画布中。这个想法是人们建立在其他人的图纸上。我找到了一个 PHP 代码,它保存在一个名为“retrieve.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 );


});

}

请有人帮帮我:)我一定错过了一些非常明显和愚蠢的东西。谢谢!

4

1 回答 1

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>

检索.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
于 2013-03-07T11:19:27.113 回答