繁体   English   中英

在画布上绘制多个框

[英]Drawing multiple boxes on canvas

在我编辑代码以将框创建为对象并将它们推入数组之前,我可以在画布上绘制多个框,并且所有这些框都会同时显示(直到我清除了画布)。 但是,现在画布上一次只显示一个框,当我绘制另一个框时,前一个框将被删除(尽管它们仍会作为对象创建并推入数组中)。 如何编辑我的代码,以便我可以在画布上绘制多个框并将它们一起显示,直到我清除画布?

代码:

const annotation = {
          xcoordi: 0,
          ycoordi: 0,
          width: 0,
          height: 0,
          printCoordinates: function () {
            console.log(`X: ${this.xcoordi}px, Y: ${this.ycoordi}px, Width: ${this.width}px, Height: ${this.height}px`);
          }
        };

//the array of all rectangles
let boundingBoxes = [];
// the actual rectangle, the one that is being 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(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.xcoordi = o.x;
    box.ycoordi = o.y;
    box.width = o.w;
    box.height = o.h;

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

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

    clearcanvas();
    // draw all the rectangles saved in the rectsRy
    boundingBoxes.map(r => {drawRect(r)})
    // draw the actual rectangle
    drawRect(o);  
}

canvas2.addEventListener("mousedown", handleMouseDown);

canvas2.addEventListener("mousemove", handleMouseMove);

canvas2.addEventListener("mouseup", handleMouseUp);

function savecanvas(){
    context2.clearRect(0, 0, canvas2.width, canvas2.height);
    var savedBoxes = boundingBoxes.slice(0);
    console.log(savedBoxes); // ok
    }

function resetcanvas(){
    context2.clearRect(0, 0, canvas2.width, canvas2.height);
    boundingBoxes.length = 0;
    console.log(boundingBoxes); // ok
    }

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 to detect the mouse position

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

任何帮助真的很感激,谢谢!

你有2个错误:

  1. 在您的代码中,您使用的是 clearcanvas(); 未定义的函数。 我已经将它替换为context2.clearRect(0, 0, canvas2.width, canvas2.height);

  2. 这更重要:您保存的对象具有以下属性: xcoordi, ycoordi, width, height , 但是在 drawRect(o) 中您使用x, y, w, h来绘制矩形,但是x, y, w, h是未定义的,因此没有绘制矩形。

请检查我的代码:

 const canvas2 = document.getElementById("canvas"); const context2 = canvas.getContext("2d"); 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`); } }; //the array of all rectangles let boundingBoxes = []; // the actual rectangle, the one that is being 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(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 = ox; box.y = oy; box.w = ow; box.h = oh; boundingBoxes.push(box); draw(); box.printCoordinates(); console.log(boundingBoxes) } function draw() { ox = start.x; // start position of x oy = start.y; // start position of y ow = mx - start.x; // width oh = my - start.y; // height //clearcanvas(); 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); } canvas2.addEventListener("mousedown", handleMouseDown); canvas2.addEventListener("mousemove", handleMouseMove); canvas2.addEventListener("mouseup", handleMouseUp); function savecanvas(){ context2.clearRect(0, 0, canvas2.width, canvas2.height); var savedBoxes = boundingBoxes.slice(0); console.log(savedBoxes); // ok } function resetcanvas(){ context2.clearRect(0, 0, canvas2.width, canvas2.height); boundingBoxes.length = 0; console.log(boundingBoxes); // ok } function drawRect(o){ context2.strokeStyle = "limegreen"; context2.lineWidth = 2; context2.beginPath(o); context2.rect(ox,oy,ow,oh); context2.stroke(); } // Function to detect the mouse position function oMousePos(canvas2, evt) { let ClientRect = canvas2.getBoundingClientRect(); return { x: Math.round(evt.clientX - ClientRect.left), y: Math.round(evt.clientY - ClientRect.top) } }
 canvas{border:1px solid;}
 <canvas id="canvas"></canvas>

 void function() { "use strict"; // Variables var canvasWidth = 180; var canvasHeight = 160; var canvas = null; var ctx = null; var rectangles = []; var isDrawing = false; var mouseStartX = 0.0; var mouseStartY = 0.0; var mouseEndX = 0.0; var mouseEndY = 0.0; // Functions // Constructor function (called with 'new') function Rectangle(x,y,width,height) { this.x = x; this.y = y; this.width = width; this.height = height; } function draw() { ctx.fillStyle = "black"; ctx.fillRect(0,0,canvasWidth,canvasHeight); ctx.strokeStyle = "limegreen"; ctx.lineWidth = 2; ctx.beginPath(); for (var i = 0; i < rectangles.length; ++i) { var rectangle = rectangles[i]; ctx.rect( rectangle.x, rectangle.y, rectangle.width, rectangle.height ); } ctx.stroke(); } function getMousePosition(e) { if (canvas && e) { var bounds = canvas.getBoundingClientRect(); return [ e.clientX - bounds.left, e.clientY - bounds.top ]; } else { return [ 0.0, 0.0 ]; } } // Event Handlers window.onmousedown = function(e) { if (!isDrawing) { isDrawing = true; // Destructuring Assignment [mouseStartX,mouseStartY] = getMousePosition(e); canvas.style.cursor = "crosshair"; } } window.onmouseup = function(e) { if (isDrawing) { isDrawing = false; // Destructuring Assignment [mouseEndX,mouseEndY] = getMousePosition(e); rectangles.push( new Rectangle( mouseStartX, mouseStartY, mouseEndX - mouseStartX, mouseEndY - mouseStartY ) ); draw(); canvas.style.cursor = "default"; } } window.onmousemove = function(e) { if (isDrawing) { // Destructuring Assignment [mouseEndX,mouseEndY] = getMousePosition(e); draw(); ctx.strokeStyle = "darkred"; ctx.lineWidth = 2; ctx.beginPath(); ctx.rect( mouseStartX, mouseStartY, mouseEndX - mouseStartX, mouseEndY - mouseStartY ); ctx.stroke(); } } // Runs when the page loads window.onload = function() { canvas = document.getElementById("canvas"); canvas.width = canvasWidth; canvas.height = canvasHeight; ctx = canvas.getContext("2d"); draw(); } }();
 canvas { display: block; margin: auto; border: solid 2px black; border-radius: 10px; }
 <!doctype html> <html> <head> <meta charset="utf-8"> </head> <body> <canvas id="canvas"></canvas> </body> </html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM