如何确定要在一张画布上绘制圆形还是矩形?

时间:2019-03-30 10:02:50

标签: html html5-canvas fabricjs geometry rect

我想按按钮确定是绘制矩形还是圆形。到目前为止有效。但是,如果我先按“圆形”按钮,然后再按“矩形”按钮,则不会删除该圆形。另一方面,是相同的。但是我希望一次只显示一个对象。用户最后按下的对象应显示。

<html>
<head>
<script src="fabric.js"></script>
</head>
   <body>
<canvas id="c" width="500" height="500"></canvas>
<button type="button" onclick="drawArc()">circle</button>
<button type="button" onclick="drawRect()">rectangle</button>

<scipt>

var canvas = new fabric.Canvas("c");
var context = canvas.getContext('2d');
var rect = new fabric.Rect({
//circle values
});
var circle = new fabric.Circle({
//rect values
});

function clear() {
     context.clearRect(0, 0, canvas.width, canvas.height);
                  }

function drawRect() {
    clear();
    canvas.add(rect);
                    }

function drawArc() {
   clear();
   canvas.add(circle);
                   }
</script>

   </body>
</html>

1 个答案:

答案 0 :(得分:0)

使用visible属性显示/隐藏画布中的对象。

演示

var canvas = new fabric.Canvas("c");
var rect = new fabric.Rect({
  width: 50,
  height: 50,
  fill: 'green',
  visible: false
});
var circle = new fabric.Circle({
  radius: 50,
  fill: 'blue',
  visible: false
});
canvas.add(rect, circle)

function drawRect() {
  circle.visible = false;
  rect.visible = true;
  canvas.requestRenderAll();
}

function drawArc() {
  circle.visible = true;
  rect.visible = false;
  canvas.requestRenderAll();
}
canvas{
  border:1px solid;
}
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.6.0/fabric.js"></script>
<button type="button" onclick="drawArc()">circle</button>
<button type="button" onclick="drawRect()">rectangle</button><br>
<canvas id="c" width="500" height="500"></canvas>