Как хранить коробки из холста? - PullRequest
0 голосов
/ 12 сентября 2018

У меня есть холст, который будет отображать видео, снятые с загрузки файла на первом слое, а второй слой позволяет рисовать прямоугольники.Поскольку я пытаюсь комментировать видео, а не неподвижные изображения, мне нужно, чтобы аннотации были сохранены, затем очищены, а затем перерисованы снова и снова, пока видео не закончится.Однако я понятия не имею, как мне это сделать, поскольку я относительно новичок в JavaScript.

Вот код, который у меня есть для рисования аннотаций:

// Drawing boxes
function handleMouseDown(e) {
    mouseX = parseInt(e.clientX - offsetX);
    mouseY = parseInt(e.clientY - offsetY);
    console.log(mouseX, mouseY);
    $("#downlog").html("Down: " + mouseX + " / " + mouseY);

    // Put your mousedown stuff here
    if (mouseIsDown) {
        console.log('1');
        canvas2.style.cursor = "crosshair";
        mouseIsDown = false;
        mouseIsUp = false;
        console.log(mouseIsDown);
    } else {
        handleMouseUp();
    }

    mouseIsDown = false;
    mouseIsUp = true;

}

function handleMouseUp(e) { // array? user input?
    mouseIsDown = false;
    startX = parseInt(e.clientX - offsetX);
    startY = parseInt(e.clientY - offsetY);
    /*if (mouseIsUp) {
        console.log('2');*/

        draw();

    }

function draw() {
/*  context2.clearRect(0, 0, canvas2.width, canvas2.height);*/
    context2.beginPath();
    context2.rect(startX, startY, mouseX - startX, mouseY - startY);
    context2.strokeStyle = "limegreen";
    context2.lineWidth = 2;
    context2.stroke();
    canvas2.style.cursor = "default";

}

$("#canvas2").mousedown(function(e) {
    handleMouseDown(e);
});

$("#canvas2").mouseup(function(e) {
    handleMouseUp(e);
});

function clearcanvas()
{
    var canvas2 = document.getElementById('canvas2'),
    context2 = canvas2.getContext("2d");
    context2.clearRect(0, 0, canvas2.width, canvas2.height);
}

Iбуду очень признателен за любую помощь, спасибо!

1 Ответ

0 голосов
/ 12 сентября 2018

Пожалуйста, прочитайте комментарии.Я надеюсь, что мой код достаточно ясен.

let c = document.getElementById("canvas");
let ctx = c.getContext("2d");
// the array of all rectangles
let rectsRy = [];
// the actual rectangle, the one that is beeing drawn
let o={};


// a variable to store the mouse position
let m = {},
// a variable to store the point where you begin to draw the rectangle    
start = {};
// a boolean 
let isDrawing = false;


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

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

function handleMouseUp(e) { // array? user input?
    c.style.cursor = "default";
    isDrawing = false;
    // push a new rectangle into the rects array
    rectsRy.push({x:o.x,y:o.y,w:o.w,h:o.h});
    }

function draw() {  
    o.x = start.x;
    o.y = start.y;
    o.w = m.x - start.x;
    o.h = m.y - start.y;
  
    clearcanvas();
    // draw all the rectangles saved in the rectsRy
    rectsRy.map(r => {drawRect(r)})
    // draw the actual rectangle
    drawRect(o);  
}

c.addEventListener("mousedown", handleMouseDown);

c.addEventListener("mousemove", handleMouseMove);

c.addEventListener("mouseup", handleMouseUp);

function clearcanvas(){
ctx.clearRect(0, 0, c.width, c.height);
}

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

// a function to detect the mouse position
// the function returns an object
function oMousePos(canvas, evt) {
  let ClientRect = canvas.getBoundingClientRect();
	return { 
	x: Math.round(evt.clientX - ClientRect.left),
	y: Math.round(evt.clientY - ClientRect.top)
  }
}
canvas{border:1px solid #d9d9d9;}
<canvas id="canvas" width="600" height="300">
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...