通过表单提交在HTML5画布上保存框的坐标

Save coordinates of box on HTML5 canvas through form submission

本文关键字:保存 坐标 表单提交 HTML5      更新时间:2023-09-26

我正在为一个分析视频的服务设计一个web前端。为了允许用户在他们上传的视频中指定感兴趣的区域,我提取了第一帧,并将其以PNG格式呈现在HTML5画布中。

<!-- HTML here -->
<script type="text/javascript">
var canvas = document.getElementById('theCanvas');
var context = canvas.getContext('2d');
var img = new Image();
img.src = document.getElementById('image').value;
context.drawImage(img, 0, 0);
</script>
<input type="hidden" id="image" value="{PHP inserts path to image here}" />

有javascript在后台,我用它来允许用户在图像上画一个框。我遇到的问题是:我如何保存所绘制的框的坐标?是可以做一个标准的POST吗?还是有javascript参与其中?

(如。框的左上角的[x,y]坐标,加上宽度和高度)

由于只有你的JS代码负责框坐标,它必须让浏览器知道坐标。

你已经有提交流程了吗?它可以通过HTML

实现,也可以完全在JS中实现(XMLHttpRequest,也经常被称为'ajax',例如在jquery中)。

如果您有基于ajax的提交,您可能不会问这个问题,所以我假设您有一个HTML

。要提交框坐标,您需要在表单中添加一些输入:
<!-- Instead of this you have a canvas with the box-selecting JS code.
     When the user makes a selection, code similar to setCoords should
     execute with the actual coordinates the user selected. -->
<input type="button" value="Set coordinates" onclick="setCoords(0,0,0,0)">
<form action="...">
  <input id="x" name="x" type="hidden">
  <input id="y" name="y" type="hidden">
  <input id="w" name="w" type="hidden">
  <input id="h" name="h" type="hidden">
  <input type="submit">
</form>
<script>
  function setCoords(x,y,w,h) {
    document.getElementById("x").value = x;
    // ...
  }
</script>