【问题标题】:Send Data to Server using Canvas使用 Canvas 向服务器发送数据
【发布时间】:2014-01-31 23:38:55
【问题描述】:

我用画布 KineticJS 绘制了一些对象, 我试过了 canvas.toDataURL("image/png"); 但是当我单击提交按钮时我不知道如何获取参数值我想将一些参数发送到服务器,

谢谢

【问题讨论】:

    标签: javascript html canvas kineticjs todataurl


    【解决方案1】:
    $.ajax({
        type: "POST",
        url: url,
        data: "yourData="+encodeURIComponent(canvas.toDataURL());,
    
    
        complete: function (result) {
            //your response
        },
        error: function () {
            //if error occured
        }
    });
    

    //根据技术在你的函数或方法或模型中接受你的数据服务器端 例如在 php 中:-echo($_POST["yourData"]);

    【讨论】:

    • 谢谢,但是如何获取服务器端的数据?例如,我有一个名为 LIGHT 的变量,它可以是真或假,我怎样才能为我的服务器端读取它的值
    【解决方案2】:

    Kinetic.Stage 上的所有对象都可以序列化为 JSON 字符串:

    首先,将stage序列化为JSON:

    var json = stage.toJSON();
    

    然后可以使用 jquery 的 ajax 方法将该 json 字符串发送到您的服务器:

    $.ajax({
      type: "POST",
      url: "http://yourSite.com/saveTheStage.php",
      data: {stageJSON: stage.toJSON()}
    })
    .done(function(respond){alert("done: "+respond);})
    .fail(function(respond){alert("fail");})
    .always(function(respond){alert("always");})
    

    在服务器上,读取接收到的 json 并将其保存为唯一的文件名(本示例使用 PHP)。

    <?php 
    
    if ( isset($_POST["stageJSON"]) && !empty($_POST["stageJSON"]) ) { 
    
        // get the stage data
        $json = $_POST['stageJSON'];
    
        // create a filename for the new image
        $file = md5(uniqid()) . '.json';
    
        // decode the image data and save it to file
        file_put_contents($file, $json);
    
        // return the filename
        echo $file;
    
    }
    
    ?>
    

    请注意,stage.toJSON 序列化 Kinetic.Stage 的属性,但不保存 Kinetic 外部的元素。

    例如,如果您的舞台有 Kinetic.Image,则 Kinetic.Image 的属性将被序列化(x,y 等),但您注入 Kinetic.Image 的图像的 .png 数据不会被序列化.

    因此,您稍后必须执行 myImage.setImage 以将 .png 数据重置为重新水合的 Kinetic.Image 的阶段。

    还要注意stage.toJSON不会序列化任何javascript变量,所以如果你的LIGHT是一个javascript变量,它就不会被序列化。

    您可以向 ajax 数据包添加更多数据以包含 LIGHT

    data: {
        stageJSON: stage.toJSON(),
        LIGHT: LIGHT
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-24
      • 2012-11-29
      • 1970-01-01
      • 2010-12-03
      • 2015-11-18
      • 2011-09-17
      相关资源
      最近更新 更多