提交时如何将表单文本转换为图像

时间:2015-08-14 06:38:53

标签: javascript jquery html ajax

enter image description here 嗨,大家好,我试图解决这种形式,当我单击表单中的提交按钮时,输出将变为图像/图片,并且字段中的所有数据也将在图像中编译。 / p>

如果你能帮助我解决这类问题,我会很高兴和感谢你的善意。

请检查图像作为我的样本。

2 个答案:

答案 0 :(得分:1)

客户端,您可以使用canvas将文字绘制为图像。



var canvas = document.querySelector('canvas');
document.querySelector('form').addEventListener('submit', function(event) {
  var ctx = canvas.getContext('2d')
    , line = 0;
  
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  [].forEach.call(event.srcElement.querySelectorAll('label'), function(label) {
    ctx.fillText(label.textContent + label.querySelector('input').value, 20, (++line) * 20);
  });
});

form, canvas { width: 500px }
canvas { height: 200px }
form > * { display: block }
form > * + * { margin-top: .5em; }
form input { width: 100% }

<form>
  <label>Name: <input name="name"></label>
  <label>Address: <input name="address"></label>
  <button>draw</button>
</form>
<canvas></canvas>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

将textarea内容复制到div,运行html2canvas并通过ajax上传图像:

&#13;
&#13;
$('#submit').click(function() {
  var abc = $('#text1').val();
  var def = $('#text2').val();
  var ghi = $('#text3').val();
  $('#container').html('<div class = text1>' + abc + '</div><div class = text2>' + def + '</div><div class = text3>' + ghi + '</div>');
  html2canvas($('#container'), {
    onrendered: function(canvas) {
      myImage = canvas.toDataURL("image/png");
      $('#image').append(canvas);
      //$.ajax({
      //data: myImage
      // ....
    }
  });
});
&#13;
#image {
  border: 1px solid black;
  margin: 10px;
  width: 100px; 
  padding: 5px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<textarea id="text1">ABC</textarea>
<textarea id="text2">DEF</textarea>
<textarea id="text3">GHI</textarea>
<button id="submit">Submit</button>
<br>Your text will appear here ->
<br>
<div id="container"></div><br>
Your image will appear here ->
<br>
<div id="image"></div>
&#13;
&#13;
&#13;