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


Passing from Javascript canvas image info AND some vars to PHP

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

我编写了一个画布,从数据输入创建图像,然后将图像数据发送到php以进行保存过程。问题是,我还需要发送1的js变量的值(在示例value1)。我不知道如何将这些信息与原始图像数据一起传递。用于绘图和保存的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文件,所以我简单地添加在url的末尾"?Dir ="+value1 "

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

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

@hendrik非常感谢你的回答,不幸的是我不能得到它的工作与json,也许是因为我不知道它。

无论如何,如果有人知道更好的方法就太好了。

我认为使用JSON是将数据发送到PHP文件的好方法。这样你就可以在Object或Array中存储多个变量。

// 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