Axis.js 20.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
/**
 * (c) 2010-2018 Torstein Honsi
 *
 * Extenstion for 3d axes
 *
 * License: www.highcharts.com/license
 */
'use strict';
import H from '../parts/Globals.js';
import '../parts/Utilities.js';
import '../parts/Axis.js';
import '../parts/Chart.js';
import '../parts/Tick.js';
var ZAxis,

    addEvent = H.addEvent,
    Axis = H.Axis,
    Chart = H.Chart,
    deg2rad = H.deg2rad,
    each = H.each,
    extend = H.extend,
    merge = H.merge,
    perspective = H.perspective,
    perspective3D = H.perspective3D,
    pick = H.pick,
    shapeArea = H.shapeArea,
    splat = H.splat,
    Tick = H.Tick,
    wrap = H.wrap;

/**
 * @optionparent xAxis
 */
var extendedOptions = {
    labels: {
        /**
         * Defines how the labels are be repositioned according to the 3D chart
         * orientation.
         * - `'offset'`: Maintain a fixed horizontal/vertical distance from the
         *      tick marks, despite the chart orientation. This is the backwards
         *      compatible behavior, and causes skewing of X and Z axes.
         * - `'chart'`: Preserve 3D position relative to the chart.
         *   This looks nice, but hard to read if the text isn't
         *   forward-facing.
         * - `'flap'`: Rotated text along the axis to compensate for the chart
         *      orientation. This tries to maintain text as legible as possible
         *      on all orientations.
         * - `'ortho'`: Rotated text along the axis direction so that the labels
         *      are orthogonal to the axis. This is very similar to `'flap'`,
         *      but prevents skewing the labels (X and Y scaling are still
         *      present).
         *
         * @validvalue ['offset', 'chart', 'flap', 'ortho']
         * @sample highcharts/3d/skewed-labels/ Skewed labels
         * @since 5.0.15
         * @product highcharts
         */
        position3d: 'offset',

        /**
         * If enabled, the axis labels will skewed to follow the perspective.
         *
         * This will fix overlapping labels and titles, but texts become less
         * legible due to the distortion.
         *
         * The final appearance depends heavily on `labels.position3d`.
         *
         * @since 5.0.15
         * @sample highcharts/3d/skewed-labels/ Skewed labels
         * @product highcharts
         */
        skew3d: false
    },
    title: {
        /**
         * Defines how the title is repositioned according to the 3D chart
         * orientation.
         * - `'offset'`: Maintain a fixed horizontal/vertical distance from the
         *   tick marks, despite the chart orientation. This is the backwards
         *   compatible behavior, and causes skewing of X and Z axes.
         * - `'chart'`: Preserve 3D position relative to the chart.
         *   This looks nice, but hard to read if the text isn't
         *   forward-facing.
         * - `'flap'`: Rotated text along the axis to compensate for the chart
         *   orientation. This tries to maintain text as legible as possible on
         *   all orientations.
         * - `'ortho'`: Rotated text along the axis direction so that the labels
         *   are orthogonal to the axis. This is very similar to `'flap'`, but
         *   prevents skewing the labels (X and Y scaling are still present).
         * - `null`: Will use the config from `labels.position3d`
         *
         * @validvalue ['offset', 'chart', 'flap', 'ortho', null]
         * @type {String}
         * @since 5.0.15
         * @sample highcharts/3d/skewed-labels/ Skewed labels
         * @product highcharts
         */
        position3d: null,

        /**
         * If enabled, the axis title will skewed to follow the perspective.
         *
          * This will fix overlapping labels and titles, but texts become less
          * legible due to the distortion.
         *
         * The final appearance depends heavily on `title.position3d`.
         *
         * A `null` value will use the config from `labels.skew3d`.
         *
         * @validvalue [false, true, null]
         * @type {Boolean}
         * @sample highcharts/3d/skewed-labels/ Skewed labels
         * @since 5.0.15
         * @product highcharts
         */
        skew3d: null
    }
};

merge(true, Axis.prototype.defaultOptions, extendedOptions);


addEvent(Axis, 'afterSetOptions', function () {
    var options;
    if (this.chart.is3d && this.chart.is3d() && this.coll !== 'colorAxis') {
        options = this.options;
        options.tickWidth = pick(options.tickWidth, 0);
        options.gridLineWidth = pick(options.gridLineWidth, 1);
    }
});

wrap(Axis.prototype, 'getPlotLinePath', function (proceed) {
    var path = proceed.apply(this, [].slice.call(arguments, 1));

    // Do not do this if the chart is not 3D
    if (!this.chart.is3d() || this.coll === 'colorAxis') {
        return path;
    }

    if (path === null) {
        return path;
    }

    var chart = this.chart,
        options3d = chart.options.chart.options3d,
        d = this.isZAxis ? chart.plotWidth : options3d.depth,
        frame = chart.frame3d;

    var pArr = [
        this.swapZ({ x: path[1], y: path[2], z: 0 }),
        this.swapZ({ x: path[1], y: path[2], z: d }),
        this.swapZ({ x: path[4], y: path[5], z: 0 }),
        this.swapZ({ x: path[4], y: path[5], z: d })
    ];

    var pathSegments = [];
    if (!this.horiz) {  // Y-Axis
        if (frame.front.visible) {
            pathSegments.push(pArr[0], pArr[2]);
        }
        if (frame.back.visible) {
            pathSegments.push(pArr[1], pArr[3]);
        }
        if (frame.left.visible) {
            pathSegments.push(pArr[0], pArr[1]);
        }
        if (frame.right.visible) {
            pathSegments.push(pArr[2], pArr[3]);
        }
    } else if (this.isZAxis) {  // Z-Axis
        if (frame.left.visible) {
            pathSegments.push(pArr[0], pArr[2]);
        }
        if (frame.right.visible) {
            pathSegments.push(pArr[1], pArr[3]);
        }
        if (frame.top.visible) {
            pathSegments.push(pArr[0], pArr[1]);
        }
        if (frame.bottom.visible) {
            pathSegments.push(pArr[2], pArr[3]);
        }
    } else {  // X-Axis
        if (frame.front.visible) {
            pathSegments.push(pArr[0], pArr[2]);
        }
        if (frame.back.visible) {
            pathSegments.push(pArr[1], pArr[3]);
        }
        if (frame.top.visible) {
            pathSegments.push(pArr[0], pArr[1]);
        }
        if (frame.bottom.visible) {
            pathSegments.push(pArr[2], pArr[3]);
        }
    }

    pathSegments = perspective(pathSegments, this.chart, false);

    return this.chart.renderer.toLineSegments(pathSegments);
});

// Do not draw axislines in 3D
wrap(Axis.prototype, 'getLinePath', function (proceed) {
    // Do not do this if the chart is not 3D
    if (!this.chart.is3d() || this.coll === 'colorAxis') {
        return proceed.apply(this, [].slice.call(arguments, 1));
    }

    return [];
});

wrap(Axis.prototype, 'getPlotBandPath', function (proceed) {
    // Do not do this if the chart is not 3D
    if (!this.chart.is3d() || this.coll === 'colorAxis') {
        return proceed.apply(this, [].slice.call(arguments, 1));
    }

    var args = arguments,
        from = args[1],
        to = args[2],
        path = [],
        fromPath = this.getPlotLinePath(from),
        toPath = this.getPlotLinePath(to);

    if (fromPath && toPath) {
        for (var i = 0; i < fromPath.length; i += 6) {
            path.push(
                'M', fromPath[i + 1], fromPath[i + 2],
                'L', fromPath[i + 4], fromPath[i + 5],
                'L', toPath[i + 4], toPath[i + 5],
                'L', toPath[i + 1], toPath[i + 2],
                'Z');
        }
    }

    return path;
});


function fix3dPosition(axis, pos, isTitle) {
    // Do not do this if the chart is not 3D
    if (!axis.chart.is3d() || axis.coll === 'colorAxis') {
        return pos;
    }

    var chart = axis.chart,
        alpha = deg2rad * chart.options.chart.options3d.alpha,
        beta = deg2rad * chart.options.chart.options3d.beta,
        positionMode = pick(
            isTitle && axis.options.title.position3d,
            axis.options.labels.position3d
        ),
        skew = pick(
            isTitle && axis.options.title.skew3d,
            axis.options.labels.skew3d
        ),
        frame = chart.frame3d,
        plotLeft = chart.plotLeft,
        plotRight = chart.plotWidth + plotLeft,
        plotTop = chart.plotTop,
        plotBottom = chart.plotHeight + plotTop,
        // Indicates we are labelling an X or Z axis on the "back" of the chart
        reverseFlap = false,
        offsetX = 0,
        offsetY = 0,
        vecX,
        vecY = { x: 0, y: 1, z: 0 };

    pos = axis.swapZ({ x: pos.x, y: pos.y, z: 0 });


    if (axis.isZAxis) {  // Z Axis
        if (axis.opposite) {
            if (frame.axes.z.top === null) {
                return {};
            }
            offsetY = pos.y - plotTop;
            pos.x = frame.axes.z.top.x;
            pos.y = frame.axes.z.top.y;
            vecX = frame.axes.z.top.xDir;
            reverseFlap = !frame.top.frontFacing;
        } else {
            if (frame.axes.z.bottom === null) {
                return {};
            }
            offsetY = pos.y - plotBottom;
            pos.x = frame.axes.z.bottom.x;
            pos.y = frame.axes.z.bottom.y;
            vecX = frame.axes.z.bottom.xDir;
            reverseFlap = !frame.bottom.frontFacing;
        }
    } else if (axis.horiz) {  // X Axis
        if (axis.opposite) {
            if (frame.axes.x.top === null) {
                return {};
            }
            offsetY = pos.y - plotTop;
            pos.y = frame.axes.x.top.y;
            pos.z = frame.axes.x.top.z;
            vecX = frame.axes.x.top.xDir;
            reverseFlap = !frame.top.frontFacing;
        } else {
            if (frame.axes.x.bottom === null) {
                return {};
            }
            offsetY = pos.y - plotBottom;
            pos.y = frame.axes.x.bottom.y;
            pos.z = frame.axes.x.bottom.z;
            vecX = frame.axes.x.bottom.xDir;
            reverseFlap = !frame.bottom.frontFacing;
        }
    } else {  // Y Axis
        if (axis.opposite) {
            if (frame.axes.y.right === null) {
                return {};
            }
            offsetX = pos.x - plotRight;
            pos.x = frame.axes.y.right.x;
            pos.z = frame.axes.y.right.z;
            vecX = frame.axes.y.right.xDir;
            // Rotate 90º on opposite edge
            vecX = { x: vecX.z, y: vecX.y, z: -vecX.x };
        } else {
            if (frame.axes.y.left === null) {
                return {};
            }
            offsetX = pos.x - plotLeft;
            pos.x = frame.axes.y.left.x;
            pos.z = frame.axes.y.left.z;
            vecX = frame.axes.y.left.xDir;
        }
    }

    if (positionMode === 'chart') {
        // Labels preserve their direction relative to the chart
        // nothing to do

    } else if (positionMode === 'flap') {
        // Labels are be rotated around the axis direction to face the screen
        if (!axis.horiz) {  // Y Axis
            vecX = { x: Math.cos(beta), y: 0, z: Math.sin(beta) };
        } else {  // X and Z Axis
            var sin = Math.sin(alpha);
            var cos = Math.cos(alpha);
            if (axis.opposite) {
                sin = -sin;
            }
            if (reverseFlap) {
                sin = -sin;
            }
            vecY = { x: vecX.z * sin, y: cos, z: -vecX.x * sin };
        }
    } else if (positionMode === 'ortho') {
        // Labels will be rotated to be ortogonal to the axis
        if (!axis.horiz) {  // Y Axis
            vecX = { x: Math.cos(beta), y: 0, z: Math.sin(beta) };
        } else {  // X and Z Axis
            var sina = Math.sin(alpha);
            var cosa = Math.cos(alpha);
            var sinb = Math.sin(beta);
            var cosb = Math.cos(beta);
            var vecZ = { x: sinb * cosa, y: -sina, z: -cosa * cosb };
            vecY = {
                x: vecX.y * vecZ.z - vecX.z * vecZ.y,
                y: vecX.z * vecZ.x - vecX.x * vecZ.z,
                z: vecX.x * vecZ.y - vecX.y * vecZ.x
            };
            var scale = 1 / Math.sqrt(
                vecY.x * vecY.x + vecY.y * vecY.y + vecY.z * vecY.z
            );
            if (reverseFlap) {
                scale = -scale;
            }
            vecY = { x: scale * vecY.x, y: scale * vecY.y, z: scale * vecY.z };
        }
    } else {  // positionMode  == 'offset'
        // Labels will be skewd to maintain vertical / horizontal offsets from
        // axis
        if (!axis.horiz) {  // Y Axis
            vecX = { x: Math.cos(beta), y: 0, z: Math.sin(beta) };
        } else {  // X and Z Axis
            vecY = {
                x: Math.sin(beta) * Math.sin(alpha),
                y: Math.cos(alpha),
                z: -Math.cos(beta) * Math.sin(alpha)
            };
        }
    }
    pos.x += offsetX * vecX.x + offsetY * vecY.x;
    pos.y += offsetX * vecX.y + offsetY * vecY.y;
    pos.z += offsetX * vecX.z + offsetY * vecY.z;

    var projected = perspective([pos], axis.chart)[0];

    if (skew) {
        // Check if the label text would be mirrored
        var isMirrored = shapeArea(perspective([
            pos,
            { x: pos.x + vecX.x, y: pos.y + vecX.y, z: pos.z + vecX.z },
            { x: pos.x + vecY.x, y: pos.y + vecY.y, z: pos.z + vecY.z }
        ], axis.chart)) < 0;
        if (isMirrored) {
            vecX = { x: -vecX.x, y: -vecX.y, z: -vecX.z };
        }

        var pointsProjected = perspective([
            { x: pos.x, y: pos.y, z: pos.z },
            { x: pos.x + vecX.x, y: pos.y + vecX.y, z: pos.z + vecX.z },
            { x: pos.x + vecY.x, y: pos.y + vecY.y, z: pos.z + vecY.z }
        ], axis.chart);

        projected.matrix = [
            pointsProjected[1].x - pointsProjected[0].x,
            pointsProjected[1].y - pointsProjected[0].y,
            pointsProjected[2].x - pointsProjected[0].x,
            pointsProjected[2].y - pointsProjected[0].y,
            projected.x,
            projected.y
        ];
        projected.matrix[4] -= projected.x * projected.matrix[0] +
            projected.y * projected.matrix[2];
        projected.matrix[5] -= projected.x * projected.matrix[1] +
            projected.y * projected.matrix[3];
    }

    return projected;
}

/*
Tick extensions
 */
wrap(Tick.prototype, 'getMarkPath', function (proceed) {
    var path = proceed.apply(this, [].slice.call(arguments, 1));

    var pArr = [
        fix3dPosition(this.axis, { x: path[1], y: path[2], z: 0 }),
        fix3dPosition(this.axis, { x: path[4], y: path[5], z: 0 })
    ];

    return this.axis.chart.renderer.toLineSegments(pArr);
});

addEvent(Tick, 'afterGetLabelPosition', function (e) {
    extend(e.pos, fix3dPosition(this.axis, e.pos));
});

wrap(Axis.prototype, 'getTitlePosition', function (proceed) {
    var pos = proceed.apply(this, [].slice.call(arguments, 1));
    return fix3dPosition(this, pos, true);
});

addEvent(Axis, 'drawCrosshair', function (e) {
    if (this.chart.is3d() && this.coll !== 'colorAxis') {
        if (e.point) {
            e.point.crosshairPos = this.isXAxis ?
                e.point.axisXpos :
                this.len - (e.point.axisYpos);
        }
    }
});

addEvent(Axis, 'destroy', function () {
    each(['backFrame', 'bottomFrame', 'sideFrame'], function (prop) {
        if (this[prop]) {
            this[prop] = this[prop].destroy();
        }
    }, this);
});

/*
Z-AXIS
*/

Axis.prototype.swapZ = function (p, insidePlotArea) {
    if (this.isZAxis) {
        var plotLeft = insidePlotArea ? 0 : this.chart.plotLeft;
        return {
            x: plotLeft + p.z,
            y: p.y,
            z: p.x - plotLeft
        };
    }
    return p;
};

ZAxis = H.ZAxis = function () {
    this.init.apply(this, arguments);
};
extend(ZAxis.prototype, Axis.prototype);
extend(ZAxis.prototype, {
    isZAxis: true,
    setOptions: function (userOptions) {
        userOptions = merge({
            offset: 0,
            lineWidth: 0
        }, userOptions);
        Axis.prototype.setOptions.call(this, userOptions);
        this.coll = 'zAxis';
    },
    setAxisSize: function () {
        Axis.prototype.setAxisSize.call(this);
        this.width = this.len = this.chart.options.chart.options3d.depth;
        this.right = this.chart.chartWidth - this.width - this.left;
    },
    getSeriesExtremes: function () {
        var axis = this,
            chart = axis.chart;

        axis.hasVisibleSeries = false;

        // Reset properties in case we're redrawing (#3353)
        axis.dataMin =
            axis.dataMax =
            axis.ignoreMinPadding =
            axis.ignoreMaxPadding = null;

        if (axis.buildStacks) {
            axis.buildStacks();
        }

        // loop through this axis' series
        each(axis.series, function (series) {

            if (series.visible || !chart.options.chart.ignoreHiddenSeries) {

                var seriesOptions = series.options,
                    zData,
                    threshold = seriesOptions.threshold;

                axis.hasVisibleSeries = true;

                // Validate threshold in logarithmic axes
                if (axis.positiveValuesOnly && threshold <= 0) {
                    threshold = null;
                }

                zData = series.zData;
                if (zData.length) {
                    axis.dataMin = Math.min(
                        pick(axis.dataMin, zData[0]),
                        Math.min.apply(null, zData)
                    );
                    axis.dataMax = Math.max(
                        pick(axis.dataMax, zData[0]),
                        Math.max.apply(null, zData)
                    );
                }
            }
        });
    }
});


/**
* Get the Z axis in addition to the default X and Y.
*/
addEvent(Chart, 'afterGetAxes', function () {
    var chart = this,
        options = this.options,
        zAxisOptions = options.zAxis = splat(options.zAxis || {});

    if (!chart.is3d()) {
        return;
    }
    this.zAxis = [];
    each(zAxisOptions, function (axisOptions, i) {
        axisOptions.index = i;
        // Z-Axis is shown horizontally, so it's kind of a X-Axis
        axisOptions.isX = true;
        var zAxis = new ZAxis(chart, axisOptions);
        zAxis.setScale();
    });
});
/**
 * Wrap getSlotWidth function to calculate individual width value
 * for each slot (#8042).
 */
wrap(Axis.prototype, 'getSlotWidth', function (proceed, tick) {
    if (this.chart.is3d() &&
        tick &&
        tick.label &&
        this.categories &&
        this.chart.frameShapes
    ) {
        var chart = this.chart,
            ticks = this.ticks,
            gridGroup = this.gridGroup.element.childNodes,
            firstGridLine = gridGroup[0].getBBox(),
            frame3DLeft = chart.frameShapes.left.getBBox(),
            options3d = chart.options.chart.options3d,
            origin = {
                x: chart.plotWidth / 2,
                y: chart.plotHeight / 2,
                z: options3d.depth / 2,
                vd: pick(options3d.depth, 1) * pick(options3d.viewDistance, 0)
            },
            labelPos,
            prevLabelPos,
            nextLabelPos,
            slotWidth,
            tickId = tick.pos,
            prevTick = ticks[tickId - 1],
            nextTick = ticks[tickId + 1];

        // Check whether the tick is not the first one and previous tick exists,
        // then calculate position of previous label.
        if (tickId !== 0 && prevTick && prevTick.label.xy) { // #8621
            prevLabelPos = perspective3D({
                x: prevTick.label.xy.x,
                y: prevTick.label.xy.y,
                z: null
            }, origin, origin.vd);
        }
        // If next label position is defined, then recalculate its position
        // basing on the perspective.
        if (nextTick && nextTick.label.xy) {
            nextLabelPos = perspective3D({
                x: nextTick.label.xy.x,
                y: nextTick.label.xy.y,
                z: null
            }, origin, origin.vd);
        }
        labelPos = {
            x: tick.label.xy.x,
            y: tick.label.xy.y,
            z: null
        };

        labelPos = perspective3D(labelPos, origin, origin.vd);

        // If tick is first one, check whether next label position is already
        // calculated, then return difference between the first and the second
        // label. If there is no next label position calculated, return the
        // difference between the first grid line and left 3d frame.
        slotWidth = Math.abs(prevLabelPos ?
            labelPos.x - prevLabelPos.x : nextLabelPos ?
                nextLabelPos.x - labelPos.x : firstGridLine.x - frame3DLeft.x
        );
        return slotWidth;
    }
    return proceed.apply(this, [].slice.call(arguments, 1));
});