我正在尝试将画布转换为Jpeg图像,并将其放入表单的隐藏字段中,然后提交表单。

  function createBlob() {
     var imageblob = canvas.toDataURL('image/jpeg', 0.5);

      document.getElementById("id_hidden_preview_field").value = imageblob; // Here we put the imageurl blob into the hidden_preview_field.

      // Here we submit the form with the
      $("#design").submit();
      alert("after submit");
}


这是表格的代码:

<div class="container">

<h2>Add a design</h2>

<form id="design" enctype="multipart/form-data" method="post"><input type="hidden" name="csrfmiddlewaretoken" value="qrGJSSQADxYItnN0TKUUPJA3JExfaFaP">
<input id="id_hidden_preview_field" name="hidden_preview_field" type="hidden"></p>
<!--<input type='submit' value='Save' />-->
<button id="gif" onclick="createBlob()">Save</button>
    </form></div>


出于某种原因,当我不放置警报时(alert(“提交后” +新的Date()。getTime());),将发送表单,而将图像保留在隐藏字段内。

而且当我输入警报时,它会毫无问题地发送出去。

这让我认为表单提交存在一个问题,该问题破坏了它需要发送的DOM元素之一。

现在是否有人真的不是异步的,如果不是,我如何确保仅在将图像复制到隐藏字段之后调用$(“#design).submit();,而不必破坏DOM元素。

非常感谢!

最佳答案

我已经修改了代码的某些部分,并使用JavaScript的addEventListener函数将click事件侦听器添加到了button而不是HTML的onclick属性。

所以这是代码:

的HTML

<canvas id="myCanvas"></canvas>
<div class="container">

<h2>Add a design</h2>
    <form id="design" enctype="multipart/form-data" method="post">
        <input type="hidden" name="csrfmiddlewaretoken" value="qrGJSSQADxYItnN0TKUUPJA3JExfaFaP" />
        <input id="id_hidden_preview_field" name="hidden_preview_field" type="hidden" />
        <button id="gif">Save</button>
    </form>
</div>


如您所见,我已经添加了canvas标记(仅用于演示)并删除了onclick按钮的Save

的JavaScript

/* Some drawing on canvas */
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.strokeText("Hello World", 10, 50);

/* Get the needed elements from the DOM */
var form = document.getElementById('design'),
    saveButton = document.getElementById('gif'),
    hiddenField = document.getElementById('id_hidden_preview_field');

/* Add click listener on save button click */
saveButton.addEventListener('click', createBlob, false);

/* The click handler function */
function createBlob() {
    var imageblob = canvas.toDataURL('image/jpeg', 0.5);

    hiddenField.value = imageblob; // Here we put the imageurl blob into the hidden_preview_field.

    // Here we submit the form with the
    form.submit();
}


在这里,我添加了一些在canvas上绘制的代码,获取并缓存了elements,并在保存按钮上添加了事件监听器。 createBlob几乎与您的代码中的相同。

您可以在JSFiddle中查看实时示例。

当您按下Save按钮时,JSFiddle会给出一个错误,因为您不能在那里提交表单。

但是,如果您打开Chrome开发工具并转到“网络”标签,则可以看到request包含Blob。您也可以在Firefox中使用Firefox开发工具或Firebug扩展名(选项卡名称为Net)进行检查。

09-26 21:59
查看更多