【问题标题】:Upload random image from local file to html5 canvas with AJAX使用 AJAX 将随机图像从本地文件上传到 html5 画布
【发布时间】:2013-03-07 20:56:25
【问题描述】:

我有一块画布,人们可以在上面涂鸦。我制作了一个按钮,可以将每个绘图提交到我的目录中名为“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 );


});

}

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

【问题讨论】:

  • 您应该在retrieve.php 中回显图像的URL(不是OK 或其他),并在您的$.ajax.done 函数中使用该结果(另外,$res 是什么?)
  • $res 是结果,这是我一直用来让我知道它是否有效的方法。 “如果达到结果,echo ok,如果没有,echo KO”。这只是为了我:)

标签: php ajax html canvas


【解决方案1】:

这样的东西应该可以工作,这两个功能结合起来;)

<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

【讨论】:

  • 非常感谢您的回答,由于某种原因它无法正常工作。我没有在画布上获得任何图像。
  • $randomImage 中存储的内容,data 中存储的内容。 IE。当你直接访问retrieve.php 时你看到了什么?
  • 我不明白为什么即使是编辑过的脚本也不起作用。如果我只是手动插入图像,它可以工作。一旦我投入 php 和 AJAX,我什么也得不到。
  • 直接访问retrieve.php会看到什么?
  • 我不太确定它是否正确。我去了本地主机并打开了php文件。我得到的只是一个空白页。我应该正常得到什么?顺便说一句,感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2013-02-13
  • 1970-01-01
  • 2012-06-10
  • 2013-02-18
  • 2017-12-18
  • 2017-12-12
  • 2013-11-23
  • 1970-01-01
相关资源
最近更新 更多