UNPKG

konva

Version:

HTML5 2d canvas library for interactive graphics, design editors, whiteboards, and diagrams.

740 lines (739 loc) 29.5 kB
import { Factory } from "../Factory.js"; import { _registerNode } from "../Global.js"; import { Shape } from "../Shape.js"; import { Util } from "../Util.js"; import { getCubicArcLength, getCubicExtremaPoints, getQuadraticArcLength, getQuadraticExtremaPoints, t2length, } from "../BezierFunctions.js"; // how many numbers each path command takes const PARAM_COUNT = { m: 2, l: 2, h: 1, v: 1, c: 6, s: 4, q: 4, t: 2, a: 7, z: 0, }; const TAU = Math.PI * 2; /** * Path constructor. * @author Jason Follas * @constructor * @memberof Konva * @augments Konva.Shape * @param {Object} config * @param {String} config.data SVG data string * @@shapeParams * @@nodeParams * @example * var path = new Konva.Path({ * x: 240, * y: 40, * data: 'M12.582,9.551C3.251,16.237,0.921,29.021,7.08,38.564l-2.36,1.689l4.893,2.262l4.893,2.262l-0.568-5.36l-0.567-5.359l-2.365,1.694c-4.657-7.375-2.83-17.185,4.352-22.33c7.451-5.338,17.817-3.625,23.156,3.824c5.337,7.449,3.625,17.813-3.821,23.152l2.857,3.988c9.617-6.893,11.827-20.277,4.935-29.896C35.591,4.87,22.204,2.658,12.582,9.551z', * fill: 'green', * scaleX: 2, * scaleY: 2 * }); */ export class Path extends Shape { constructor(config) { super(config); this.dataArray = []; this.pathLength = 0; this._readDataAttribute(); this.on('dataChange.konva', function () { this._readDataAttribute(); }); } _readDataAttribute() { this.dataArray = Path.parsePathData(this.data()); this.pathLength = Path.getPathLength(this.dataArray); } _sceneFunc(context) { const ca = this.dataArray; // context position context.beginPath(); let isClosed = false; for (let n = 0; n < ca.length; n++) { const c = ca[n].command; const p = ca[n].points; switch (c) { case 'L': context.lineTo(p[0], p[1]); break; case 'M': context.moveTo(p[0], p[1]); break; case 'C': context.bezierCurveTo(p[0], p[1], p[2], p[3], p[4], p[5]); break; case 'Q': context.quadraticCurveTo(p[0], p[1], p[2], p[3]); break; case 'A': context.ellipse(p[0], p[1], p[2], p[3], p[6], p[4], p[4] + p[5], !p[7]); break; case 'z': isClosed = true; context.closePath(); break; } } if (!isClosed && !this.hasFill()) { context.strokeShape(this); } else { context.fillStrokeShape(this); } } getWidth() { return this.getSelfRect().width; } getHeight() { return this.getSelfRect().height; } getSelfRect() { const points = []; this.dataArray.forEach(function (data) { if (data.command === 'A') { // the two end points, plus the angles where the ellipse turns back on // either axis, when they fall inside the sweep. Together they are the // exact bounds of the segment const [cx, cy, rx, ry, start, dTheta, psi] = data.points; const cos = Math.cos(psi), sin = Math.sin(psi); const end = Path.getPointOnEllipticalArc(cx, cy, rx, ry, start + dTheta, psi); points.push(data.start.x, data.start.y, end.x, end.y); const tx = Math.atan2(-ry * sin, rx * cos); const ty = Math.atan2(ry * cos, rx * sin); [tx, tx + Math.PI, ty, ty + Math.PI].forEach((t) => { // how far into the sweep t is, in the direction of the sweep const k = ((((t - start) * Math.sign(dTheta)) % TAU) + TAU) % TAU; if (k < Math.abs(dTheta)) { const point = Path.getPointOnEllipticalArc(cx, cy, rx, ry, t, psi); points.push(point.x, point.y); } }); } else if (data.command === 'C') { // the two end points, plus the points where the curve turns back on // either axis. Together they are the exact bounds of the segment points.push(data.start.x, data.start.y, data.points[4], data.points[5], ...getCubicExtremaPoints(data.start.x, data.start.y, data.points[0], data.points[1], data.points[2], data.points[3], data.points[4], data.points[5])); } else if (data.command === 'Q') { // same as 'C'. Note that 'q', 'T' and 't' are all normalised to 'Q' by // the parser, so this one branch covers every quadratic segment points.push(data.start.x, data.start.y, data.points[2], data.points[3], ...getQuadraticExtremaPoints(data.start.x, data.start.y, data.points[0], data.points[1], data.points[2], data.points[3])); } else { points.push(...data.points); } }); return Util._getPointsRect(points); } /** * Return length of the path. * @method * @name Konva.Path#getLength * @returns {Number} length * @example * var length = path.getLength(); */ getLength() { return this.pathLength; } /** * Get point on path at specific length of the path * @method * @name Konva.Path#getPointAtLength * @param {Number} length length * @returns {Object} point {x,y} point * @example * var point = path.getPointAtLength(10); */ getPointAtLength(length) { return Path.getPointAtLengthOfDataArray(length, this.dataArray); } static getLineLength(x1, y1, x2, y2) { return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); } static getPathLength(dataArray) { let pathLength = 0; for (let i = 0; i < dataArray.length; ++i) { pathLength += dataArray[i].pathLength; } return pathLength; } // The optional cursor is for sequential lookups within one continuous subpath. static getPointAtLengthOfDataArray(length, dataArray, cursor) { var _a, _b; let points, i = (_a = cursor === null || cursor === void 0 ? void 0 : cursor.index) !== null && _a !== void 0 ? _a : 0, offset = (_b = cursor === null || cursor === void 0 ? void 0 : cursor.offset) !== null && _b !== void 0 ? _b : 0, ii = dataArray.length; if (!ii) { return null; } // Negative spacing can move a text glyph back into an earlier segment. while (i > 0 && length <= offset) { offset -= dataArray[--i].pathLength; } length -= offset; while (i < ii && length > dataArray[i].pathLength) { const segmentLength = dataArray[i].pathLength; length -= segmentLength; offset += segmentLength; ++i; } if (cursor && i < ii) { cursor.index = i; cursor.offset = offset; } if (i === ii) { // past the end: the end of the last segment i--; length = dataArray[i].pathLength; } if (length < 0.01) { const cmd = dataArray[i].command; if (cmd === 'M') { points = dataArray[i].points.slice(0, 2); return { x: points[0], y: points[1], }; } else { return { x: dataArray[i].start.x, y: dataArray[i].start.y, }; } } const cp = dataArray[i]; const p = cp.points; switch (cp.command) { case 'L': case 'z': return Path.getPointOnLine(length, cp.start.x, cp.start.y, p[0], p[1]); case 'C': return Path.getPointOnCubicBezier(t2length(length, cp.pathLength, (i) => { return getCubicArcLength([cp.start.x, p[0], p[2], p[4]], [cp.start.y, p[1], p[3], p[5]], i); }), cp.start.x, cp.start.y, p[0], p[1], p[2], p[3], p[4], p[5]); case 'Q': return Path.getPointOnQuadraticBezier(t2length(length, cp.pathLength, (i) => { return getQuadraticArcLength([cp.start.x, p[0], p[2]], [cp.start.y, p[1], p[3]], i); }), cp.start.x, cp.start.y, p[0], p[1], p[2], p[3]); case 'A': return Path.getPointOnEllipticalArc(p[0], p[1], p[2], p[3], // on a circle angle is proportional to distance, so the walk is only // needed for a real ellipse p[2] === p[3] ? p[4] + (p[5] * length) / cp.pathLength : Path._walkArc(p, length).theta, p[6]); } return null; } static getPointOnLine(dist, P1x, P1y, P2x, P2y, fromX, fromY) { fromX = fromX !== null && fromX !== void 0 ? fromX : P1x; fromY = fromY !== null && fromY !== void 0 ? fromY : P1y; const len = this.getLineLength(P1x, P1y, P2x, P2y); if (len < 1e-10) { return { x: P1x, y: P1y }; } if (P2x === P1x) { // Vertical line return { x: fromX, y: fromY + (P2y > P1y ? dist : -dist) }; } const m = (P2y - P1y) / (P2x - P1x); const run = Math.sqrt((dist * dist) / (1 + m * m)) * (P2x < P1x ? -1 : 1); const rise = m * run; if (Math.abs(fromY - P1y - m * (fromX - P1x)) < 1e-10) { return { x: fromX + run, y: fromY + rise }; } const u = ((fromX - P1x) * (P2x - P1x) + (fromY - P1y) * (P2y - P1y)) / (len * len); const ix = P1x + u * (P2x - P1x); const iy = P1y + u * (P2y - P1y); const pRise = this.getLineLength(fromX, fromY, ix, iy); const pRun = Math.sqrt(dist * dist - pRise * pRise); const adjustedRun = Math.sqrt((pRun * pRun) / (1 + m * m)) * (P2x < P1x ? -1 : 1); const adjustedRise = m * adjustedRun; return { x: ix + adjustedRun, y: iy + adjustedRise }; } static getPointOnCubicBezier(pct, P1x, P1y, P2x, P2y, P3x, P3y, P4x, P4y) { function CB1(t) { return t * t * t; } function CB2(t) { return 3 * t * t * (1 - t); } function CB3(t) { return 3 * t * (1 - t) * (1 - t); } function CB4(t) { return (1 - t) * (1 - t) * (1 - t); } const x = P4x * CB1(pct) + P3x * CB2(pct) + P2x * CB3(pct) + P1x * CB4(pct); const y = P4y * CB1(pct) + P3y * CB2(pct) + P2y * CB3(pct) + P1y * CB4(pct); return { x, y }; } static getPointOnQuadraticBezier(pct, P1x, P1y, P2x, P2y, P3x, P3y) { function QB1(t) { return t * t; } function QB2(t) { return 2 * t * (1 - t); } function QB3(t) { return (1 - t) * (1 - t); } const x = P3x * QB1(pct) + P2x * QB2(pct) + P1x * QB3(pct); const y = P3y * QB1(pct) + P2y * QB2(pct) + P1y * QB3(pct); return { x, y }; } static getPointOnEllipticalArc(cx, cy, rx, ry, theta, psi) { const cosPsi = Math.cos(psi), sinPsi = Math.sin(psi); const pt = { x: rx * Math.cos(theta), y: ry * Math.sin(theta), }; return { x: cx + (pt.x * cosPsi - pt.y * sinPsi), y: cy + (pt.x * sinPsi + pt.y * cosPsi), }; } /* * get parsed data array from the data * string. V, v, H, h, and l data are converted to * L data for the purpose of high performance Path * rendering */ static parsePathData(data) { // Path Data Segment must begin with a moveTo //m (x y)+ Relative moveTo (subsequent points are treated as lineTo) //M (x y)+ Absolute moveTo (subsequent points are treated as lineTo) //l (x y)+ Relative lineTo //L (x y)+ Absolute LineTo //h (x)+ Relative horizontal lineTo //H (x)+ Absolute horizontal lineTo //v (y)+ Relative vertical lineTo //V (y)+ Absolute vertical lineTo //z (closepath) //Z (closepath) //c (x1 y1 x2 y2 x y)+ Relative Bezier curve //C (x1 y1 x2 y2 x y)+ Absolute Bezier curve //q (x1 y1 x y)+ Relative Quadratic Bezier //Q (x1 y1 x y)+ Absolute Quadratic Bezier //t (x y)+ Shorthand/Smooth Relative Quadratic Bezier //T (x y)+ Shorthand/Smooth Absolute Quadratic Bezier //s (x2 y2 x y)+ Shorthand/Smooth Relative Bezier curve //S (x2 y2 x y)+ Shorthand/Smooth Absolute Bezier curve //a (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+ Relative Elliptical Arc //A (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+ Absolute Elliptical Arc // return early if data is not defined if (!data) { return []; } // command string let cs = data; // command chars const cc = [ 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z', 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A', ]; // convert white spaces to commas cs = cs.replace(new RegExp(' ', 'g'), ','); // create pipes so that we can split the data for (let n = 0; n < cc.length; n++) { cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]); } // create array const arr = cs.split('|'); const ca = []; const coords = []; // init context point let cpx = 0; let cpy = 0; // start of the current subpath: where z draws back to let spx = 0; let spy = 0; const re = /([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/gi; let match; for (let n = 1; n < arr.length; n++) { let str = arr[n]; let c = str.charAt(0); str = str.slice(1); coords.length = 0; while ((match = re.exec(str))) { coords.push(match[0]); } const p = []; // Track param position for A/a commands: 0..6 => rx, ry, psi, fa, fs, x, y let arcParamIndex = c === 'A' || c === 'a' ? 0 : -1; for (let j = 0, jlen = coords.length; j < jlen; j++) { let token = coords[j]; // SVGO merges the arc flags with the number that follows them: // "01.5.5" is fa=0 fs=1 x=.5 y=.5 while ((arcParamIndex === 3 || arcParamIndex === 4) && token.length > 1 && (token[0] === '0' || token[0] === '1')) { p.push(+token[0]); arcParamIndex++; token = token.slice(1); } const parsed = parseFloat(token); p.push(isNaN(parsed) ? 0 : parsed); if (arcParamIndex >= 0) { arcParamIndex = (arcParamIndex + 1) % 7; } } let pIndex = 0; while (pIndex < p.length) { // z takes no numbers, and a command with too few of them ("L20" // with no y) is dropped rather than parsed into a NaN segment if (p.length - pIndex < PARAM_COUNT[c.toLowerCase()] || c === 'z' || c === 'Z') { break; } let cmd = ''; let points = []; const startX = cpx, startY = cpy; // Move var from within the switch to up here (jshint) let prevCmd, ctlPtx, ctlPty; // Ss, Tt let rx, ry, psi, fa, fs, x1, y1; // Aa // convert l, H, h, V, and v to L switch (c) { // Note: Keep the lineTo's above the moveTo's in this switch case 'l': cpx += p[pIndex++]; cpy += p[pIndex++]; cmd = 'L'; points.push(cpx, cpy); break; case 'L': cpx = p[pIndex++]; cpy = p[pIndex++]; points.push(cpx, cpy); break; // Note: lineTo handlers need to be above this point case 'm': cpx += p[pIndex++]; cpy += p[pIndex++]; cmd = 'M'; spx = cpx; spy = cpy; points.push(cpx, cpy); c = 'l'; // subsequent points are treated as relative lineTo break; case 'M': cpx = p[pIndex++]; cpy = p[pIndex++]; cmd = 'M'; spx = cpx; spy = cpy; points.push(cpx, cpy); c = 'L'; // subsequent points are treated as absolute lineTo break; case 'h': cpx += p[pIndex++]; cmd = 'L'; points.push(cpx, cpy); break; case 'H': cpx = p[pIndex++]; cmd = 'L'; points.push(cpx, cpy); break; case 'v': cpy += p[pIndex++]; cmd = 'L'; points.push(cpx, cpy); break; case 'V': cpy = p[pIndex++]; cmd = 'L'; points.push(cpx, cpy); break; case 'C': points.push(p[pIndex++], p[pIndex++], p[pIndex++], p[pIndex++]); cpx = p[pIndex++]; cpy = p[pIndex++]; points.push(cpx, cpy); break; case 'c': points.push(cpx + p[pIndex++], cpy + p[pIndex++], cpx + p[pIndex++], cpy + p[pIndex++]); cpx += p[pIndex++]; cpy += p[pIndex++]; cmd = 'C'; points.push(cpx, cpy); break; case 'S': ctlPtx = cpx; ctlPty = cpy; prevCmd = ca[ca.length - 1]; if ((prevCmd === null || prevCmd === void 0 ? void 0 : prevCmd.command) === 'C') { ctlPtx = cpx + (cpx - prevCmd.points[2]); ctlPty = cpy + (cpy - prevCmd.points[3]); } points.push(ctlPtx, ctlPty, p[pIndex++], p[pIndex++]); cpx = p[pIndex++]; cpy = p[pIndex++]; cmd = 'C'; points.push(cpx, cpy); break; case 's': ctlPtx = cpx; ctlPty = cpy; prevCmd = ca[ca.length - 1]; if ((prevCmd === null || prevCmd === void 0 ? void 0 : prevCmd.command) === 'C') { ctlPtx = cpx + (cpx - prevCmd.points[2]); ctlPty = cpy + (cpy - prevCmd.points[3]); } points.push(ctlPtx, ctlPty, cpx + p[pIndex++], cpy + p[pIndex++]); cpx += p[pIndex++]; cpy += p[pIndex++]; cmd = 'C'; points.push(cpx, cpy); break; case 'Q': points.push(p[pIndex++], p[pIndex++]); cpx = p[pIndex++]; cpy = p[pIndex++]; points.push(cpx, cpy); break; case 'q': points.push(cpx + p[pIndex++], cpy + p[pIndex++]); cpx += p[pIndex++]; cpy += p[pIndex++]; cmd = 'Q'; points.push(cpx, cpy); break; case 'T': ctlPtx = cpx; ctlPty = cpy; prevCmd = ca[ca.length - 1]; if ((prevCmd === null || prevCmd === void 0 ? void 0 : prevCmd.command) === 'Q') { ctlPtx = cpx + (cpx - prevCmd.points[0]); ctlPty = cpy + (cpy - prevCmd.points[1]); } cpx = p[pIndex++]; cpy = p[pIndex++]; cmd = 'Q'; points.push(ctlPtx, ctlPty, cpx, cpy); break; case 't': ctlPtx = cpx; ctlPty = cpy; prevCmd = ca[ca.length - 1]; if ((prevCmd === null || prevCmd === void 0 ? void 0 : prevCmd.command) === 'Q') { ctlPtx = cpx + (cpx - prevCmd.points[0]); ctlPty = cpy + (cpy - prevCmd.points[1]); } cpx += p[pIndex++]; cpy += p[pIndex++]; cmd = 'Q'; points.push(ctlPtx, ctlPty, cpx, cpy); break; case 'A': case 'a': // per SVG, the radii are used as absolute values rx = Math.abs(p[pIndex++]); ry = Math.abs(p[pIndex++]); psi = p[pIndex++]; fa = p[pIndex++]; fs = p[pIndex++]; x1 = cpx; y1 = cpy; if (c === 'a') { cpx += p[pIndex++]; cpy += p[pIndex++]; } else { cpx = p[pIndex++]; cpy = p[pIndex++]; } cmd = 'A'; // per SVG, an arc between coincident end points is omitted // and a zero radius makes it a straight line if (cpx === x1 && cpy === y1) { continue; } else if (!rx || !ry) { cmd = 'L'; points.push(cpx, cpy); } else { points = this.convertEndpointToCenterParameterization(x1, y1, cpx, cpy, fa, fs, rx, ry, psi); } break; } ca.push({ command: cmd || c, points: points, start: { x: startX, y: startY, }, pathLength: this.calcLength(startX, startY, cmd || c, points), }); } if (c === 'z' || c === 'Z') { // per SVG, z is a line back to the start of the subpath, which then // becomes the current point ca.push({ command: 'z', points: [spx, spy], start: { x: cpx, y: cpy }, pathLength: this.getLineLength(cpx, cpy, spx, spy), }); cpx = spx; cpy = spy; } } return ca; } /** * Walks an arc in one degree steps, accumulating its length. Returns the * angle `length` along the arc, or its end angle and total length when * `length` is past the end. */ static _walkArc(points, length) { const [cx, cy, rx, ry, start, dTheta] = points; const steps = Math.max(1, Math.ceil(Math.abs(dTheta) / (Math.PI / 180))); // the arc length does not depend on the x-axis rotation psi, so it is left out let p1 = Path.getPointOnEllipticalArc(cx, cy, rx, ry, start, 0); let prev = start; let len = 0; for (let i = 1; i <= steps; i++) { const t = start + (dTheta * i) / steps; const p2 = Path.getPointOnEllipticalArc(cx, cy, rx, ry, t, 0); const d = Path.getLineLength(p1.x, p1.y, p2.x, p2.y); if (len + d >= length) { return { theta: prev + (t - prev) * ((length - len) / d), length }; } len += d; p1 = p2; prev = t; } return { theta: prev, length: len }; } static calcLength(x, y, cmd, points) { const path = Path; switch (cmd) { case 'L': return path.getLineLength(x, y, points[0], points[1]); case 'C': return getCubicArcLength([x, points[0], points[2], points[4]], [y, points[1], points[3], points[5]], 1); case 'Q': return getQuadraticArcLength([x, points[0], points[2]], [y, points[1], points[3]], 1); case 'A': return path._walkArc(points, Infinity).length; } return 0; } static convertEndpointToCenterParameterization(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg) { // Derived from: http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes const psi = psiDeg * (Math.PI / 180.0); const xp = (Math.cos(psi) * (x1 - x2)) / 2.0 + (Math.sin(psi) * (y1 - y2)) / 2.0; const yp = (-1 * Math.sin(psi) * (x1 - x2)) / 2.0 + (Math.cos(psi) * (y1 - y2)) / 2.0; const lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry); if (lambda > 1) { rx *= Math.sqrt(lambda); ry *= Math.sqrt(lambda); } let f = Math.sqrt((rx * rx * (ry * ry) - rx * rx * (yp * yp) - ry * ry * (xp * xp)) / (rx * rx * (yp * yp) + ry * ry * (xp * xp))); if (fa === fs) { f *= -1; } if (isNaN(f)) { f = 0; } const cxp = (f * rx * yp) / ry; const cyp = (f * -ry * xp) / rx; const cx = (x1 + x2) / 2.0 + Math.cos(psi) * cxp - Math.sin(psi) * cyp; const cy = (y1 + y2) / 2.0 + Math.sin(psi) * cxp + Math.cos(psi) * cyp; const vMag = function (v) { return Math.sqrt(v[0] * v[0] + v[1] * v[1]); }; const vRatio = function (u, v) { return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v)); }; const vAngle = function (u, v) { return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v)); }; const theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]); const u = [(xp - cxp) / rx, (yp - cyp) / ry]; const v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry]; let dTheta = vAngle(u, v); if (vRatio(u, v) <= -1) { dTheta = Math.PI; } if (vRatio(u, v) >= 1) { dTheta = 0; } if (fs === 0 && dTheta > 0) { dTheta = dTheta - 2 * Math.PI; } if (fs === 1 && dTheta < 0) { dTheta = dTheta + 2 * Math.PI; } return [cx, cy, rx, ry, theta, dTheta, psi, fs]; } } Path.prototype.className = 'Path'; Path.prototype._attrsAffectingSize = ['data']; _registerNode(Path); /** * get/set SVG path data string. This method * also automatically parses the data string * into a data array. Currently supported SVG data: * M, m, L, l, H, h, V, v, Q, q, T, t, C, c, S, s, A, a, Z, z * @name Konva.Path#data * @method * @param {String} data svg path string * @returns {String} * @example * // get data * var data = path.data(); * * // set data * path.data('M200,100h100v50z'); */ Factory.addGetterSetter(Path, 'data'); /** * get width of the path. It is computed from the path data and cannot be set * @name Konva.Path#width * @method * @returns {Number} * @example * var width = path.width(); */ /** * get height of the path. It is computed from the path data and cannot be set * @name Konva.Path#height * @method * @returns {Number} * @example * var height = path.height(); */