簡體   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