未选中时在Fabric Textbox上绘制边框 [英] Draw border on Fabric Textbox when it's not selected

查看:809
本文介绍了未选中时在Fabric Textbox上绘制边框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此jsfiddle中我有一个Fabric(版本1.x)文本框,该文本框具有红色选中时为边框,可编辑文本时为蓝色边框.当文本框未选中时,我需要一个边框.如何实现?

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

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);

推荐答案

您可以覆盖文本框对象的渲染方法.并为文本对象绘制边框.

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>

这篇关于未选中时在Fabric Textbox上绘制边框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆