Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw border on Fabric Textbox when it's not selected

Tags:

fabricjs

In this jsfiddle I have a Fabric (version 1.x) Textbox that has a red border when it's selected and a blue border when the text is editable. What I need is a border when the TextBox is not selected. How to achieve that?

HTML

<canvas id="c" width="300" height="300"></canvas>

Javascript

var canvas = new fabric.Canvas('c');

var text = new fabric.Textbox("Some Text", {
  left: 50,
  top: 50,
  width: 100,
  fontSize: 12,
  fontFamily: 'Arial',
  backgroundColor: 'yellow',
  borderColor: 'red',
  editingBorderColor: 'blue',
  padding: 2
});

canvas.add(text);
like image 219
ps0604 Avatar asked Jul 08 '18 14:07

ps0604


1 Answers

You can override render method of textbox object. And draw border for text object.

DEMO

var canvas = new fabric.Canvas('c');

var originalRender = fabric.Textbox.prototype._render;
fabric.Textbox.prototype._render = function(ctx) {
  originalRender.call(this, ctx);
  //Don't draw border if it is active(selected/ editing mode)
  if (this.active) return;
  if(this.showTextBoxBorder){
    var w = this.width,
      h = this.height,
      x = -this.width / 2,
      y = -this.height / 2;
    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.lineTo(x + w, y);
    ctx.lineTo(x + w, y + h);
    ctx.lineTo(x, y + h);
    ctx.lineTo(x, y);
    ctx.closePath();
    var stroke = ctx.strokeStyle;
    ctx.strokeStyle = this.textboxBorderColor;
    ctx.stroke();
    ctx.strokeStyle = stroke;
  }
}
fabric.Textbox.prototype.cacheProperties = fabric.Textbox.prototype.cacheProperties.concat('active');

var text = new fabric.Textbox("Some Text\n some more text", {
  left: 50,
  top: 50,
  width: 100,
  fontSize: 12,
  fontFamily: 'Arial',
  backgroundColor: 'yellow',
  borderColor: 'red',
  editingBorderColor: 'blue',
  padding: 2,
  showTextBoxBorder: true,
  textboxBorderColor: 'green'
});
canvas.add(text);
canvas{
 border : 2px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.7/fabric.js"></script>
<canvas id="c" width="300" height="300"></canvas>
like image 106
Durga Avatar answered Nov 20 '22 08:11

Durga