从Javascript画布图像信息和一些变量传递到PHP

时间:2013-06-03 09:58:14

标签: php javascript canvas

首先,抱歉我的英语不好,我是意大利人。我对编程有点新意,但对于我的办公室,我需要创建一个有点复杂的脚本(至少对我而言)。在解释问题之前,我将解释我在做什么。

我编写了一个从数据输入创建图像的画布,然后我将图像数据发送到php以进行保存。问题是我还需要发送一个js变量值(在示例中为value1)。我无法弄清楚如何将这些信息与原始图像数据一起传递。 img绘图和保存的js代码。我需要将value1传递给save.php

button.addEventListener("click",function(){
            //saving the values of the form
    var value1 = document.getElementById("value1").value;
            //text on the canvas
    var value1X = (maxWidth-ctx.measureText(value1).width)/2+500;
            //drawing the inputed text on the canvas
    ctx.drawImage(img,0,0);
        ctx.fillText(value1,value1X,maxHeight);
            //getting the image url and sending it to save.php for the saving process
        var imageURL = c.toDataURL("image/png");
        var ajax = new XMLHttpRequest();
        ajax.open("POST", 'saving.php', false);
        ajax.setRequestHeader('Content-Type','application/upload');
        ajax.send(imageURL);
 }, false);

这是PHP文件:

<?php
if (isset($GLOBALS[HTTP_RAW_POST_DATA])) {
$imageData = $GLOBALS[HTTP_RAW_POST_DATA];
$imageData = str_replace('data:image/png;base64,', '', $imageData);
$imageData = str_replace(' ', '+', $imageData);
$data = base64_decode($imageData);
    //here i need the value1 value from the javascript
$dirname = "value1";
$filename = "header_top.png";
$newdir = mkdir($dirname);
$path = ("the/path/to".$dirname."/");
$fp = fopen($path.$filename, 'wb');
fwrite($fp, $data);
fclose($fp);
}

我希望我能够解释自己,这样你就可以帮助我。

非常感谢。

编辑: 我想我明白了,我的意思是它现在有效,但我不知道它是否正确的做法。 事实是,我正在调用一个php文件,所以我简单地添加到网址的末尾“?dir =”+ value1,它可以工作。

    ajax.open("POST", 'saving.php?dir='+value1, false);
    ajax.setRequestHeader('Content-Type','application/upload');
    ajax.send(imageURL);

在php文件中我只需调用$ _GET ['dir']来获取值。

@hendrik非常感谢你的回答,不幸的是我无法与json合作,也许因为我不知道。

无论如何,如果有人知道更好的方式会很好。

1 个答案:

答案 0 :(得分:0)

我认为使用JSON是将数据发送到PHP文件的好方法。这样,您可以在对象或数组中存储多个变量。

// Store your data in an Object
var imageData = {
    url: 'http://adsadsf.com',
    name: 'foobar.gif',
    width: 500,
    height: 400,
    directory: 'img/'
}

var ajax = new XMLHttpRequest();
ajax.open("POST", 'saving.php', false);
// Send the imageData object as JSON
ajax.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
ajax.send(JSON.stringify(imageData));

不幸的是,我对PHP没有足够的了解来解释如何处理收到的JSON数据,但我想你可以使用json_decode方法。

有关JSON的更多信息:http://www.json.org/js.html