如何标记在JavaScript画布上创建的框?

时间:2018-10-23 08:40:19

标签: javascript html json canvas

我有一个画布,可以在其中绘制框,然后将这些框的x-y坐标以及宽度和高度保存为JSON格式。但是,我想知道是否有可能在一个字段中为每个对象(例如bluecar,redcar等)输入唯一的名称,该名称也将出现在JSON输出中吗?如下面的JSON输出所示,坐标和其他信息正确显示,但是我想添加对象的名称,以区分其他对象。

var canvas = document.getElementById("canvas");
var context = canvas.getContext('2d');
var canvas2 = document.getElementById("canvas2");
var context2 = canvas2.getContext('2d');
let isDrawing = false;

const annotation = {
  x: 0,
  y: 0,
  w: 0,
  h: 0,
  printCoordinates: function() {
    console.log(`X: ${this.x}px, Y: ${this.y}px, Width: ${this.w}px, Height: ${this.h}px`);
  }
};

let boundingBoxes = [];

function handleMouseDown(e) {
  start = oMousePos(canvas2, e);
  isDrawing = true;
  //console.log(start.x, start.y);
  canvas2.style.cursor = "crosshair";
}

function handleMouseMove(e) {
  if (isDrawing) {
    m = oMousePos(canvas2, e);
    draw();
  }
}


function handleMouseUp(e) {
  canvas2.style.cursor = "default";
  isDrawing = false;

  const box = Object.create(annotation);
  box.x = o.x;
  box.y = o.y;
  box.w = o.w;
  box.h = o.h;

  boundingBoxes.push(box);
  draw();
  box.printCoordinates();
  console.log(boundingBoxes)
}

canvas2.addEventListener("mousedown", handleMouseDown);

canvas2.addEventListener("mousemove", handleMouseMove);

canvas2.addEventListener("mouseup", handleMouseUp);

function draw() {
  o.x = start.x; // start position of x
  o.y = start.y; // start position of y
  o.w = m.x - start.x; // width
  o.h = m.y - start.y; // height

  context2.clearRect(0, 0, canvas2.width, canvas2.height); //////***********
  // draw all the rectangles saved in the rectsRy
  boundingBoxes.map(r => {
    drawRect(r)
  })
  // draw the actual rectangle
  drawRect(o);
}

function drawRect(o) {
  context2.strokeStyle = "limegreen";
  context2.lineWidth = 2;
  context2.beginPath(o);
  context2.rect(o.x, o.y, o.w, o.h);
  context2.stroke();
}

function oMousePos(canvas2, evt) {
  let ClientRect = canvas2.getBoundingClientRect();
  return {
    x: Math.round(evt.clientX - ClientRect.left),
    y: Math.round(evt.clientY - ClientRect.top)
  }
}

document.getElementById('save').addEventListener('click', function() {
  // retrieve the canvas data
  var canvasContents = canvas.toDataURL(); // a data URL of the current
  // canvas

  var string = JSON.stringify(boundingBoxes, null, 2);

  // create a blob object representing the data as a JSON string
  var file = new Blob([string], {
    type: 'application/json'
  });

  // trigger a click event on an <a> tag to open the file explorer
  var a = document.createElement('a');
  a.href = URL.createObjectURL(file);
  a.download = 'data.json';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title></title>
</head>

<body>

  Import Image: <input type="file" id="fileUpload" name="fileUpload" multiple/>

  <p>
    <div id="buttons1">
      <button id="reset" onclick="resetcanvas()">Reset Annotations</button> &nbsp
      <button id="save">
    			<span>Export Annotations</span>
    		</button>

      <div id="canvases" align="middle" style="position:relative; width:1580px; height:700px; overflow: scroll; ">
        <canvas id="canvas2" align="middle" style="z-index: 1; position: absolute; left: 125px; top: 0px; "></canvas>
        <canvas id="canvas" align="middle" style="z-index: 0; position: absolute; left: 125px; top: 0px; "></canvas>
      </div>

      <p></p>
      <br>
      <span></span>
    </div>
    <p></p>
    <div id="button ">

    </div>

JSON输出:

[
  {
    "x": 356,
    "y": 235,
    "w": -105,
    "h": -146
  },
  {
    "x": 185,
    "y": 238,
    "w": -51,
    "h": -93
  }
]

任何帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:0)

我添加了一些变量来绕过您的错误...我以为那只是复制/粘贴错误。

handleMouseUp上,您可以添加box.name = "Name";来包含姓名

var canvas = document.getElementById("canvas");
var context = canvas.getContext('2d');
var canvas2 = document.getElementById("canvas2");
var context2 = canvas2.getContext('2d');
let isDrawing = false;

const annotation = {
  x: 0, y: 0, w: 0, h: 0,
  printCoordinates: function() {
    console.log(`X: ${this.x}px, Y: ${this.y}px, Width: ${this.w}px, Height: ${this.h}px`);
  }
};

var o = annotation;
var start;

let boundingBoxes = [];

function handleMouseUp(e) {
  canvas2.style.cursor = "default";
  isDrawing = false;

  const box = Object.create(annotation);
  box.x = o.x;
  box.y = o.y;
  box.w = o.w;
  box.h = o.h;
  box.name = "Name";

  boundingBoxes.push(box);
  draw();
  box.printCoordinates();
  //console.log(boundingBoxes)
}

function handleMouseDown(e) {
  start = oMousePos(canvas2, e);
  isDrawing = true;
  //console.log(start.x, start.y);
  canvas2.style.cursor = "crosshair";
}

function handleMouseMove(e) {
  if (isDrawing) {
    m = oMousePos(canvas2, e);
    draw();
  }
}

canvas2.addEventListener("mousedown", handleMouseDown);

canvas2.addEventListener("mousemove", handleMouseMove);

canvas2.addEventListener("mouseup", handleMouseUp);

function draw() {
  o.x = start.x; // start position of x
  o.y = start.y; // start position of y
  o.w = m.x - start.x; // width
  o.h = m.y - start.y; // height

  context2.clearRect(0, 0, canvas2.width, canvas2.height); //////***********
  // draw all the rectangles saved in the rectsRy
  boundingBoxes.map(r => {
    drawRect(r)
  })
  // draw the actual rectangle
  drawRect(o);
}

function drawRect(o) {
  context2.strokeStyle = "limegreen";
  context2.lineWidth = 2;
  context2.beginPath(o);
  context2.rect(o.x, o.y, o.w, o.h);
  context2.stroke();
}

function oMousePos(canvas2, evt) {
  let ClientRect = canvas2.getBoundingClientRect();
  return {
    x: Math.round(evt.clientX - ClientRect.left),
    y: Math.round(evt.clientY - ClientRect.top)
  }
}

document.getElementById('save').addEventListener('click', function() {
  // retrieve the canvas data
  var canvasContents = canvas.toDataURL(); // a data URL of the current
  // canvas

  var string = JSON.stringify(boundingBoxes, null, 2);

  // create a blob object representing the data as a JSON string
  var file = new Blob([string], {
    type: 'application/json'
  });

  // trigger a click event on an <a> tag to open the file explorer
  var a = document.createElement('a');
  a.href = URL.createObjectURL(file);
  a.download = 'data.json';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title></title>
</head>

<body>

  Import Image: <input type="file" id="fileUpload" name="fileUpload" multiple/>

  <p>
    <div id="buttons1">
      <button id="reset" onclick="resetcanvas()">Reset Annotations</button> &nbsp
      <button id="save"><span>Export Annotations</span></button>

      <div id="canvases" align="middle" style="position:relative; width:1580px; height:700px; overflow: scroll; ">
        <canvas id="canvas2" align="middle" style="z-index: 1; position: absolute; left: 125px; top: 0px; "></canvas>
        <canvas id="canvas" align="middle" style="z-index: 0; position: absolute; left: 125px; top: 0px; "></canvas>
      </div>

      <p></p>
      <br>
      <span></span>
    </div>
    <p></p>
    <div id="button ">

    </div>