Text.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import BaseElement from './BaseElement'
  2. import { drawText } from '../utils/draw'
  3. import DragElement from './DragElement'
  4. import {
  5. transformPointOnElement,
  6. splitTextLines,
  7. getTextElementSize
  8. } from '../utils'
  9. import { checkIsAtRectangleInner } from '../utils/checkHit'
  10. // 文本元素类
  11. export default class Text extends BaseElement {
  12. constructor(opts = {}, app) {
  13. super(opts, app)
  14. // 拖拽元素实例
  15. this.dragElement = new DragElement(this, this.app, {
  16. lockRatio: true
  17. })
  18. this.text = opts.text || ''
  19. this.style.fillStyle =
  20. opts.style?.fillStyle || this.app.state.strokeStyle || '#000'
  21. this.style.fontSize = opts.style?.fontSize || this.app.state.fontSize || 18
  22. this.style.lineHeightRatio = opts.style?.lineHeightRatio || 1.5
  23. this.style.fontFamily =
  24. opts.style?.fontFamily ||
  25. this.app.state.fontFamily ||
  26. '微软雅黑, Microsoft YaHei'
  27. }
  28. // 序列化
  29. serialize() {
  30. let base = super.serialize()
  31. return {
  32. ...base,
  33. text: this.text
  34. }
  35. }
  36. // 渲染到画布
  37. render() {
  38. let { width, height } = this
  39. this.warpRender(({ halfWidth, halfHeight }) => {
  40. // 画布中心点修改了,所以元素的坐标也要相应修改
  41. drawText(this.app.ctx, this, -halfWidth, -halfHeight, width, height)
  42. })
  43. // 激活时显示拖拽框
  44. this.renderDragElement()
  45. }
  46. // 检测是否被击中
  47. isHit(x, y) {
  48. let rp = transformPointOnElement(x, y, this)
  49. return checkIsAtRectangleInner(this, rp)
  50. }
  51. // 更新包围框
  52. updateRect(x, y, width, height) {
  53. let { text, style } = this
  54. // 新字号 = 新高度 / 行数
  55. let fontSize = Math.floor(
  56. height / splitTextLines(text).length / style.lineHeightRatio
  57. )
  58. this.style.fontSize = fontSize
  59. super.updateRect(x, y, width, height)
  60. }
  61. // 字号改不了更新尺寸
  62. updateTextSize() {
  63. let { width, height } = getTextElementSize(this)
  64. this.width = width
  65. this.height = height
  66. }
  67. }