在画布上绘制多个框

时间:2018-09-24 03:16:58

标签: javascript object canvas drawing

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

代码:

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 个答案:

答案 0 :(得分:3)

您有2个错误:

  1. 在您的代码中,您正在使用clearcanvas();未定义的功能。我已将其替换为context2.clearRect(0, 0, canvas2.width, canvas2.height);

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

请检查我的代码:

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 = o.x;
    box.y = o.y;
    box.w = o.w;
    box.h = 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();
    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(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)
  }
}
canvas{border:1px solid;}

答案 1 :(得分:-1)

@OnLifecycleEvent
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;
}

相关问题