diff --git a/src/graphic/shape/text.js b/src/graphic/shape/text.js index 0e1200ac2..15156cb79 100644 --- a/src/graphic/shape/text.js +++ b/src/graphic/shape/text.js @@ -1,5 +1,6 @@ const Util = require('../../util/common'); const Shape = require('../shape'); +const RectUtil = require('../util/rect'); let textWidthCacheCounter = 0; let textWidthCache = {}; @@ -147,7 +148,7 @@ class Text extends Shape { const self = this; const attrs = self._attrs.attrs; const { x, y, textAlign, textBaseline } = attrs; - const width = self._getTextWidth(); // attrs.width + let width = self._getTextWidth(); // attrs.width if (!width) { return { minX: x, @@ -156,7 +157,17 @@ class Text extends Shape { maxY: y }; } - const height = self._getTextHeight(); // attrs.height + let height = self._getTextHeight(); // attrs.height + + if (attrs.rotate) { + const rotatedBox = RectUtil.calcRotatedBox({ + width, + height, + rotate: attrs.rotate + }); + width = rotatedBox.width; + height = rotatedBox.height; + } const point = { x, y: y - height diff --git a/src/graphic/util/rect.js b/src/graphic/util/rect.js new file mode 100644 index 000000000..19f8beec9 --- /dev/null +++ b/src/graphic/util/rect.js @@ -0,0 +1,12 @@ +const Rect = { + calcRotatedBox({ width, height, rotate }) { + const absRotate = Math.abs(rotate); + return { + width: Math.abs(width * Math.cos(absRotate) + height * Math.sin(absRotate)), + height: Math.abs(height * Math.cos(absRotate) + width * Math.sin(absRotate)) + }; + } +}; + +module.exports = Rect; + diff --git a/test/unit/graphic/shape/text-spec.js b/test/unit/graphic/shape/text-spec.js index 812c5acb2..8a99791f0 100644 --- a/test/unit/graphic/shape/text-spec.js +++ b/test/unit/graphic/shape/text-spec.js @@ -168,6 +168,28 @@ describe('Text', function() { expect(bbox.width).to.equal(28.67578125); expect(bbox.height).to.equal(48); canvas.draw(); + }); + + it('rotate', function() { + const text = new Text({ + attrs: { + x: 100, + y: 50, + text: 'haha\nHello\nworld', + textAlign: 'end', + textBaseline: 'middle', + fontSize: 12, + lineHeight: 18, + lineWidth: 1, + rotate: Math.PI / 2 + } + }); + canvas.add(text); + // bbox + const bbox = text.getBBox(); + expect(bbox.width).to.equal(48); + expect(bbox.height).to.equal(28.67578125); + canvas.draw(); document.body.removeChild(dom); }); });