graphic.js 27.9 KB
Newer Older
L
lang 已提交
1 2 3 4
define(function(require) {

    'use strict';

L
lang 已提交
5 6
    var zrUtil = require('zrender/core/util');

L
lang 已提交
7
    var pathTool = require('zrender/tool/path');
8
    var Path = require('zrender/graphic/Path');
L
lang 已提交
9
    var colorTool = require('zrender/tool/color');
10
    var matrix = require('zrender/core/matrix');
L
lang 已提交
11
    var vector = require('zrender/core/vector');
P
pah100 已提交
12 13
    var Transformable = require('zrender/mixin/Transformable');
    var BoundingRect = require('zrender/core/BoundingRect');
14 15 16 17

    var round = Math.round;
    var mathMax = Math.max;
    var mathMin = Math.min;
18

19 20 21 22 23 24 25 26 27 28 29 30
    var graphic = {};

    graphic.Group = require('zrender/container/Group');

    graphic.Image = require('zrender/graphic/Image');

    graphic.Text = require('zrender/graphic/Text');

    graphic.Circle = require('zrender/graphic/shape/Circle');

    graphic.Sector = require('zrender/graphic/shape/Sector');

L
lang 已提交
31 32
    graphic.Ring = require('zrender/graphic/shape/Ring');

33 34 35 36
    graphic.Polygon = require('zrender/graphic/shape/Polygon');

    graphic.Polyline = require('zrender/graphic/shape/Polyline');

L
lang 已提交
37
    graphic.Rect = require('zrender/graphic/shape/Rect');
38 39 40

    graphic.Line = require('zrender/graphic/shape/Line');

L
lang 已提交
41 42
    graphic.BezierCurve = require('zrender/graphic/shape/BezierCurve');

43 44
    graphic.Arc = require('zrender/graphic/shape/Arc');

L
lang 已提交
45 46
    graphic.CompoundPath = require('zrender/graphic/CompoundPath');

L
tweak  
lang 已提交
47 48 49 50
    graphic.LinearGradient = require('zrender/graphic/LinearGradient');

    graphic.RadialGradient = require('zrender/graphic/RadialGradient');

P
pah100 已提交
51
    graphic.BoundingRect = BoundingRect;
L
lang 已提交
52

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
    /**
     * Extend shape with parameters
     */
    graphic.extendShape = function (opts) {
        return Path.extend(opts);
    };

    /**
     * Extend path
     */
    graphic.extendPath = function (pathData, opts) {
        return pathTool.extendFromString(pathData, opts);
    };

    /**
     * Create a path element from path data string
P
pah100 已提交
69 70 71 72
     * @param {string} pathData
     * @param {Object} opts
     * @param {module:zrender/core/BoundingRect} rect
     * @param {string} [layout=cover] 'center' or 'cover'
73
     */
P
pah100 已提交
74
    graphic.makePath = function (pathData, opts, rect, layout) {
75
        var path = pathTool.createFromString(pathData, opts);
L
lang 已提交
76
        var boundingRect = path.getBoundingRect();
77
        if (rect) {
L
lang 已提交
78
            var aspect = boundingRect.width / boundingRect.height;
P
pah100 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97

            if (layout === 'center') {
                // Set rect to center, keep width / height ratio.
                var width = rect.height * aspect;
                var height;
                if (width <= rect.width) {
                    height = rect.height;
                }
                else {
                    width = rect.width;
                    height = width / aspect;
                }
                var cx = rect.x + rect.width / 2;
                var cy = rect.y + rect.height / 2;

                rect.x = cx - width / 2;
                rect.y = cy - height / 2;
                rect.width = width;
                rect.height = height;
L
lang 已提交
98
            }
P
pah100 已提交
99

O
tweak  
Ovilia 已提交
100
            graphic.resizePath(path, rect);
101 102 103 104 105 106 107 108 109 110 111 112
        }
        return path;
    };

    graphic.mergePath = pathTool.mergePath,

    /**
     * Resize a path to fit the rect
     * @param {module:zrender/graphic/Path} path
     * @param {Object} rect
     */
    graphic.resizePath = function (path, rect) {
L
tweak  
lang 已提交
113
        if (!path.applyTransform) {
114 115 116 117 118
            return;
        }

        var pathRect = path.getBoundingRect();

L
lang 已提交
119
        var m = pathRect.calculateTransform(rect);
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

        path.applyTransform(m);
    };

    /**
     * Sub pixel optimize line for canvas
     *
     * @param {Object} param
     * @param {Object} [param.shape]
     * @param {number} [param.shape.x1]
     * @param {number} [param.shape.y1]
     * @param {number} [param.shape.x2]
     * @param {number} [param.shape.y2]
     * @param {Object} [param.style]
     * @param {number} [param.style.lineWidth]
     * @return {Object} Modified param
     */
    graphic.subPixelOptimizeLine = function (param) {
        var subPixelOptimize = graphic.subPixelOptimize;
        var shape = param.shape;
        var lineWidth = param.style.lineWidth;

        if (round(shape.x1 * 2) === round(shape.x2 * 2)) {
            shape.x1 = shape.x2 = subPixelOptimize(shape.x1, lineWidth, true);
        }
        if (round(shape.y1 * 2) === round(shape.y2 * 2)) {
            shape.y1 = shape.y2 = subPixelOptimize(shape.y1, lineWidth, true);
L
lang 已提交
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
        return param;
    };

    /**
     * Sub pixel optimize rect for canvas
     *
     * @param {Object} param
     * @param {Object} [param.shape]
     * @param {number} [param.shape.x]
     * @param {number} [param.shape.y]
     * @param {number} [param.shape.width]
     * @param {number} [param.shape.height]
     * @param {Object} [param.style]
     * @param {number} [param.style.lineWidth]
     * @return {Object} Modified param
     */
    graphic.subPixelOptimizeRect = function (param) {
        var subPixelOptimize = graphic.subPixelOptimize;
        var shape = param.shape;
        var lineWidth = param.style.lineWidth;
        var originX = shape.x;
        var originY = shape.y;
        var originWidth = shape.width;
        var originHeight = shape.height;
        shape.x = subPixelOptimize(shape.x, lineWidth, true);
        shape.y = subPixelOptimize(shape.y, lineWidth, true);
        shape.width = Math.max(
            subPixelOptimize(originX + originWidth, lineWidth, false) - shape.x,
            originWidth === 0 ? 0 : 1
        );
        shape.height = Math.max(
            subPixelOptimize(originY + originHeight, lineWidth, false) - shape.y,
            originHeight === 0 ? 0 : 1
        );
        return param;
    };

    /**
     * Sub pixel optimize for canvas
     *
     * @param {number} position Coordinate, such as x, y
     * @param {number} lineWidth Should be nonnegative integer.
     * @param {boolean=} positiveOrNegative Default false (negative).
     * @return {number} Optimized position.
     */
    graphic.subPixelOptimize = function (position, lineWidth, positiveOrNegative) {
        // Assure that (position + lineWidth / 2) is near integer edge,
        // otherwise line will be fuzzy in canvas.
        var doubledPosition = round(position * 2);
        return (doubledPosition + round(lineWidth)) % 2 === 0
            ? doubledPosition / 2
            : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
    };

L
lang 已提交
202 203 204 205 206
    function hasFillOrStroke(fillOrStroke) {
        return fillOrStroke != null && fillOrStroke != 'none';
    }

    function liftColor(color) {
207
        return typeof color === 'string' ? colorTool.lift(color, -0.1) : color;
L
lang 已提交
208 209
    }

L
lang 已提交
210
    /**
L
lang 已提交
211
     * @private
L
lang 已提交
212
     */
213
    function cacheElementStl(el) {
L
lang 已提交
214 215 216 217 218 219
        if (el.__hoverStlDirty) {
            var stroke = el.style.stroke;
            var fill = el.style.fill;

            // Create hoverStyle on mouseover
            var hoverStyle = el.__hoverStl;
L
lang 已提交
220
            hoverStyle.fill = hoverStyle.fill
L
lang 已提交
221
                || (hasFillOrStroke(fill) ? liftColor(fill) : null);
L
lang 已提交
222
            hoverStyle.stroke = hoverStyle.stroke
L
lang 已提交
223
                || (hasFillOrStroke(stroke) ? liftColor(stroke) : null);
L
lang 已提交
224 225 226

            var normalStyle = {};
            for (var name in hoverStyle) {
S
sushuang 已提交
227 228
                // See comment in `doSingleEnterHover`.
                if (hoverStyle[name] != null) {
229 230
                    normalStyle[name] = el.style[name];
                }
L
lang 已提交
231 232 233 234 235 236
            }

            el.__normalStl = normalStyle;

            el.__hoverStlDirty = false;
        }
237 238 239 240 241 242 243 244 245 246 247 248
    }

    /**
     * @private
     */
    function doSingleEnterHover(el) {
        if (el.__isHover) {
            return;
        }

        cacheElementStl(el);

L
lang 已提交
249 250 251 252
        if (el.useHoverLayer) {
            el.__zr && el.__zr.addHover(el, el.__hoverStl);
        }
        else {
S
sushuang 已提交
253 254 255 256 257 258 259 260 261 262 263 264 265
            // styles can be:
            // {
            //     label: {
            //         normal: {
            //             show: false,
            //             position: 'outside',
            //             fontSize: 18
            //         },
            //         emphasis: {
            //             show: true
            //         }
            //     }
            // },
S
sushuang 已提交
266
            // where properties of `emphasis` may not appear in `normal`. We previously use
S
sushuang 已提交
267 268
            // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
            // But consider rich text, it is impossible to cover all properties in merge.
S
sushuang 已提交
269 270
            // So we use merge mode when setting style here, where only properties that
            // is not `null/undefined` can be set. The disadventage: null/undefined can not
S
sushuang 已提交
271 272
            // be used to remove style any more in `emphasis`.
            el.style.extendFrom(el.__hoverStl);
P
pah100 已提交
273
            el.dirty(false);
L
lang 已提交
274 275
            el.z2 += 1;
        }
276 277

        el.__isHover = true;
278
    }
L
lang 已提交
279 280

    /**
281
     * @inner
L
lang 已提交
282
     */
283 284 285 286 287
    function doSingleLeaveHover(el) {
        if (!el.__isHover) {
            return;
        }

L
lang 已提交
288
        var normalStl = el.__normalStl;
L
lang 已提交
289 290 291 292
        if (el.useHoverLayer) {
            el.__zr && el.__zr.removeHover(el);
        }
        else {
S
sushuang 已提交
293
            // Consider null/undefined value, should use
S
sushuang 已提交
294 295
            // `setStyle` but not `extendFrom(stl, true)`.
            normalStl && el.setStyle(normalStl);
L
lang 已提交
296 297
            el.z2 -= 1;
        }
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

        el.__isHover = false;
    }

    /**
     * @inner
     */
    function doEnterHover(el) {
        el.type === 'group'
            ? el.traverse(function (child) {
                if (child.type !== 'group') {
                    doSingleEnterHover(child);
                }
            })
            : doSingleEnterHover(el);
    }

    function doLeaveHover(el) {
        el.type === 'group'
            ? el.traverse(function (child) {
                if (child.type !== 'group') {
                    doSingleLeaveHover(child);
                }
            })
            : doSingleLeaveHover(el);
L
lang 已提交
323 324 325 326 327 328
    }

    /**
     * @inner
     */
    function setElementHoverStl(el, hoverStl) {
L
lang 已提交
329 330
        // If element has sepcified hoverStyle, then use it instead of given hoverStyle
        // Often used when item group has a label element and it's hoverStyle is different
L
lang 已提交
331
        el.__hoverStl = el.hoverStyle || hoverStl || {};
L
lang 已提交
332
        el.__hoverStlDirty = true;
333 334 335 336

        if (el.__isHover) {
            cacheElementStl(el);
        }
L
lang 已提交
337
    }
338

L
lang 已提交
339 340 341
    /**
     * @inner
     */
342 343 344 345 346
    function onElementMouseOver(e) {
        if (this.__hoverSilentOnTouch && e.zrByTouch) {
            return;
        }

L
lang 已提交
347
        // Only if element is not in emphasis status
L
lang 已提交
348
        !this.__isEmphasis && doEnterHover(this);
L
lang 已提交
349 350
    }

L
lang 已提交
351 352 353
    /**
     * @inner
     */
354 355 356 357 358
    function onElementMouseOut(e) {
        if (this.__hoverSilentOnTouch && e.zrByTouch) {
            return;
        }

L
lang 已提交
359
        // Only if element is not in emphasis status
L
lang 已提交
360
        !this.__isEmphasis && doLeaveHover(this);
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
    }

    /**
     * @inner
     */
    function enterEmphasis() {
        this.__isEmphasis = true;
        doEnterHover(this);
    }

    /**
     * @inner
     */
    function leaveEmphasis() {
        this.__isEmphasis = false;
        doLeaveHover(this);
377
    }
L
lang 已提交
378

379
    /**
380 381
     * Set hover style of element.
     * This method can be called repeatly without side-effects.
L
lang 已提交
382
     * @param {module:zrender/Element} el
L
lang 已提交
383
     * @param {Object} [hoverStyle]
384 385 386 387 388 389 390 391 392 393 394
     * @param {Object} [opt]
     * @param {boolean} [opt.hoverSilentOnTouch=false]
     *        In touch device, mouseover event will be trigger on touchstart event
     *        (see module:zrender/dom/HandlerProxy). By this mechanism, we can
     *        conviniently use hoverStyle when tap on touch screen without additional
     *        code for compatibility.
     *        But if the chart/component has select feature, which usually also use
     *        hoverStyle, there might be conflict between 'select-highlight' and
     *        'hover-highlight' especially when roam is enabled (see geo for example).
     *        In this case, hoverSilentOnTouch should be used to disable hover-highlight
     *        on touch device.
395
     */
396 397 398
    graphic.setHoverStyle = function (el, hoverStyle, opt) {
        el.__hoverSilentOnTouch = opt && opt.hoverSilentOnTouch;

L
lang 已提交
399 400 401 402 403 404 405
        el.type === 'group'
            ? el.traverse(function (child) {
                if (child.type !== 'group') {
                    setElementHoverStl(child, hoverStyle);
                }
            })
            : setElementHoverStl(el, hoverStyle);
406 407

        // Duplicated function will be auto-ignored, see Eventful.js.
L
lang 已提交
408 409
        el.on('mouseover', onElementMouseOver)
          .on('mouseout', onElementMouseOut);
410 411 412 413

        // Emphasis, normal can be triggered manually
        el.on('emphasis', enterEmphasis)
          .on('normal', leaveEmphasis);
414
    };
L
lang 已提交
415

P
pah100 已提交
416 417 418 419
    /**
     * Set basic textStyle properties.
     * @param {Object|module:zrender/graphic/Style} style
     * @param {module:echarts/model/Model} model
S
sushuang 已提交
420
     * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
P
pah100 已提交
421 422 423 424 425 426 427 428 429 430
     * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
     */
    graphic.setTextStyle = function (style, textStyleModel, specifiedTextStyle, opt) {
        setTextStyleCommon(style, textStyleModel, opt);
        specifiedTextStyle && zrUtil.extend(style, specifiedTextStyle);
        style.dirty && style.dirty();

        return style;
    };

L
lang 已提交
431 432
    /**
     * Set text option in the style
L
tweak  
lang 已提交
433
     * @param {Object} textStyle
L
lang 已提交
434 435
     * @param {module:echarts/model/Model} labelModel
     * @param {string} color
S
sushuang 已提交
436
     * @param {boolean} isEmphasis
L
lang 已提交
437
     */
S
sushuang 已提交
438 439 440 441 442 443
    graphic.setText = function (textStyle, labelModel, color, isEmphasis) {
        setTextStyleCommon(textStyle, labelModel, {
            isRectText: true,
            forMerge: isEmphasis,
            defaultTextColor: color
        });
L
lang 已提交
444 445
    };

P
pah100 已提交
446 447
    /**
     * {
P
tweak  
pah100 已提交
448
     *      disableBox: boolean, Whether diable drawing box of block (outer most).
P
pah100 已提交
449 450
     *      isRectText: boolean,
     *      autoColor: string, specify a color when color is 'auto',
S
sushuang 已提交
451 452 453 454
     *                 for textFill, textStroke, textBackgroundColor, and textBorderColor,
     *      defaultTextColor: defaultTextColor,
     *      forceRich: boolean,
     *      forMerge: boolean
P
pah100 已提交
455 456 457
     * }
     */
    function setTextStyleCommon(textStyle, textStyleModel, opt) {
S
sushuang 已提交
458 459 460
        // Consider there will be abnormal when merge hover style to normal style if given default value.
        var forMerge = opt && opt.forMerge;

P
pah100 已提交
461
        if (opt && opt.isRectText) {
S
sushuang 已提交
462
            textStyle.textPosition = textStyleModel.getShallow('position') || (forMerge ? null : 'inside');
P
pah100 已提交
463 464 465 466
            textStyle.textOffset = textStyleModel.getShallow('offset');
            var labelRotate = textStyleModel.getShallow('rotate');
            labelRotate != null && (labelRotate *= Math.PI / 180);
            textStyle.textRotation = labelRotate;
S
sushuang 已提交
467
            textStyle.textDistance = textStyleModel.getShallow('distance') || (forMerge ? null : 5);
P
pah100 已提交
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
        }

        var ecModel = textStyleModel.ecModel;
        var globalTextStyle = ecModel && ecModel.option.textStyle;

        var rich = textStyleModel.getShallow('rich');
        var richResult;
        if (rich) {
            richResult = {};
            for (var name in rich) {
                if (rich.hasOwnProperty(name)) {
                    // Cascade is supported in rich.
                    var richTextStyle = textStyleModel.getModel(['rich', name]);
                    // In rich, never `disableBox`.
                    setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt);
                }
            }
        }
        textStyle.rich = richResult;

P
tweak  
pah100 已提交
488
        setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, true);
P
pah100 已提交
489 490 491 492 493 494 495 496

        if (opt && opt.forceRich && !opt.textStyle) {
            opt.textStyle = {};
        }

        return textStyle;
    }

P
tweak  
pah100 已提交
497
    function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isBlock) {
S
sushuang 已提交
498 499 500 501 502 503 504 505 506
        var textPosition = textStyle.textPosition;
        textStyle.textFill = getAutoColor(textStyleModel.getTextColor(), opt) || (
            (opt && opt.forMerge)
                ? null
                : (textPosition && textPosition.indexOf('inside') >= 0)
                ? '#fff'
                : (opt && opt.defaultTextColor)
        );

P
pah100 已提交
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
        textStyle.textStroke = getAutoColor(
            textStyleModel.getShallow('textBorderColor')
                || (globalTextStyle && globalTextStyle.textBorderColor)
        );
        textStyle.textLineWidth = textStyleModel.getShallow('textBorderWidth');
        textStyle.textFont = textStyleModel.getFont();

        textStyle.textAlign = textStyleModel.getShallow('align');
        textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
            || textStyleModel.getShallow('baseline');

        textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
        textStyle.textWidth = textStyleModel.getShallow('width');
        textStyle.textHeight = textStyleModel.getShallow('height');
        textStyle.textTag = textStyleModel.getShallow('tag');

P
tweak  
pah100 已提交
523
        if (!opt || !isBlock || !opt.disableBox) {
P
pah100 已提交
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
            textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
            textStyle.textPadding = textStyleModel.getShallow('padding');
            textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
            textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
            textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');

            textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
            textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
            textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
            textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
        }

        textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
            || (globalTextStyle && globalTextStyle.textShadowColor);
        textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
            || (globalTextStyle && globalTextStyle.textShadowBlur);
        textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
            || (globalTextStyle && globalTextStyle.textShadowOffsetX);
        textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
            || (globalTextStyle && globalTextStyle.textShadowOffsetY);
    }

    function getAutoColor(color, opt) {
        return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
    }

P
pah100 已提交
550 551 552 553 554 555 556 557 558 559 560
    graphic.getFont = function (opt, ecModel) {
        var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
        return [
            // FIXME in node-canvas fontWeight is before fontStyle
            opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
            opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
            (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
            opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
        ].join(' ');
    };

L
lang 已提交
561 562 563 564 565
    function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
        if (typeof dataIndex === 'function') {
            cb = dataIndex;
            dataIndex = null;
        }
1
100pah 已提交
566 567 568 569
        // Do not check 'animation' property directly here. Consider this case:
        // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
        // but its parent model (`seriesModel`) does.
        var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
L
lang 已提交
570

L
lang 已提交
571 572
        if (animationEnabled) {
            var postfix = isUpdate ? 'Update' : '';
1
100pah 已提交
573 574 575
            var duration = animatableModel.getShallow('animationDuration' + postfix);
            var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
            var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
L
lang 已提交
576
            if (typeof animationDelay === 'function') {
1
100pah 已提交
577 578 579 580 581 582
                animationDelay = animationDelay(
                    dataIndex,
                    animatableModel.getAnimationDelayParams
                        ? animatableModel.getAnimationDelayParams(el, dataIndex)
                        : null
                );
L
lang 已提交
583
            }
L
lang 已提交
584 585 586 587
            if (typeof duration === 'function') {
                duration = duration(dataIndex);
            }

L
lang 已提交
588
            duration > 0
S
sushuang 已提交
589
                ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
P
pah100 已提交
590
                : (el.stopAnimation(), el.attr(props), cb && cb());
L
lang 已提交
591 592
        }
        else {
P
pah100 已提交
593
            el.stopAnimation();
L
lang 已提交
594 595
            el.attr(props);
            cb && cb();
L
lang 已提交
596
        }
597
    }
1
100pah 已提交
598

599 600 601 602
    /**
     * Update graphic element properties with or without animation according to the configuration in series
     * @param {module:zrender/Element} el
     * @param {Object} props
603
     * @param {module:echarts/model/Model} [animatableModel]
L
lang 已提交
604 605 606 607 608 609 610 611 612 613
     * @param {number} [dataIndex]
     * @param {Function} [cb]
     * @example
     *     graphic.updateProps(el, {
     *         position: [100, 100]
     *     }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
     *     // Or
     *     graphic.updateProps(el, {
     *         position: [100, 100]
     *     }, seriesModel, function () { console.log('Animation done!'); });
614
     */
L
lang 已提交
615 616 617
    graphic.updateProps = function (el, props, animatableModel, dataIndex, cb) {
        animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
    };
618 619 620 621 622

    /**
     * Init graphic element properties with or without animation according to the configuration in series
     * @param {module:zrender/Element} el
     * @param {Object} props
623
     * @param {module:echarts/model/Model} [animatableModel]
L
lang 已提交
624
     * @param {number} [dataIndex]
625 626
     * @param {Function} cb
     */
L
lang 已提交
627 628 629
    graphic.initProps = function (el, props, animatableModel, dataIndex, cb) {
        animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
    };
630

631 632 633 634 635
    /**
     * Get transform matrix of target (param target),
     * in coordinate of its ancestor (param ancestor)
     *
     * @param {module:zrender/mixin/Transformable} target
P
pah100 已提交
636
     * @param {module:zrender/mixin/Transformable} [ancestor]
637 638 639 640
     */
    graphic.getTransform = function (target, ancestor) {
        var mat = matrix.identity([]);

P
tweak  
pah100 已提交
641 642 643
        while (target && target !== ancestor) {
            matrix.mul(mat, target.getLocalTransform(), mat);
            target = target.parent;
644
        }
P
tweak  
pah100 已提交
645

646 647 648 649 650
        return mat;
    };

    /**
     * Apply transform to an vertex.
P
pah100 已提交
651 652 653 654
     * @param {Array.<number>} target [x, y]
     * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
     *      + Transform matrix: like [1, 0, 0, 1, 0, 0]
     *      + {position, rotation, scale}, the same as `zrender/Transformable`.
655 656 657
     * @param {boolean=} invert Whether use invert matrix.
     * @return {Array.<number>} [x, y]
     */
P
pah100 已提交
658 659 660 661 662
    graphic.applyTransform = function (target, transform, invert) {
        if (transform && !zrUtil.isArrayLike(transform)) {
            transform = Transformable.getLocalTransform(transform);
        }

663 664 665
        if (invert) {
            transform = matrix.invert([], transform);
        }
P
pah100 已提交
666
        return vector.applyTransform([], target, transform);
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
    };

    /**
     * @param {string} direction 'left' 'right' 'top' 'bottom'
     * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
     * @param {boolean=} invert Whether use invert matrix.
     * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
     */
    graphic.transformDirection = function (direction, transform, invert) {

        // Pick a base, ensure that transform result will not be (0, 0).
        var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
            ? 1 : Math.abs(2 * transform[4] / transform[0]);
        var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
            ? 1 : Math.abs(2 * transform[4] / transform[2]);

        var vertex = [
            direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
            direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
        ];

        vertex = graphic.applyTransform(vertex, transform, invert);

        return Math.abs(vertex[0]) > Math.abs(vertex[1])
            ? (vertex[0] > 0 ? 'right' : 'left')
            : (vertex[1] > 0 ? 'bottom' : 'top');
    };

L
lang 已提交
695
    /**
P
pah100 已提交
696 697
     * Apply group transition animation from g1 to g2.
     * If no animatableModel, no animation.
L
lang 已提交
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
     */
    graphic.groupTransition = function (g1, g2, animatableModel, cb) {
        if (!g1 || !g2) {
            return;
        }

        function getElMap(g) {
            var elMap = {};
            g.traverse(function (el) {
                if (!el.isGroup && el.anid) {
                    elMap[el.anid] = el;
                }
            });
            return elMap;
        }
        function getAnimatableProps(el) {
            var obj = {
                position: vector.clone(el.position),
                rotation: el.rotation
            };
            if (el.shape) {
                obj.shape = zrUtil.extend({}, el.shape);
            }
            return obj;
        }
        var elMap1 = getElMap(g1);

        g2.traverse(function (el) {
            if (!el.isGroup && el.anid) {
                var oldEl = elMap1[el.anid];
                if (oldEl) {
                    var newProp = getAnimatableProps(el);
                    el.attr(getAnimatableProps(oldEl));
                    graphic.updateProps(el, newProp, animatableModel, el.dataIndex);
                }
                // else {
                //     if (el.previousProps) {
                //         graphic.updateProps
                //     }
                // }
            }
        });
    };

742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
    /**
     * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
     * @param {Object} rect {x, y, width, height}
     * @return {Array.<Array.<number>>} A new clipped points.
     */
    graphic.clipPointsByRect = function (points, rect) {
        return zrUtil.map(points, function (point) {
            var x = point[0];
            x = mathMax(x, rect.x);
            x = mathMin(x, rect.x + rect.width);
            var y = point[1];
            y = mathMax(y, rect.y);
            y = mathMin(y, rect.y + rect.height);
            return [x, y];
        });
    };

    /**
     * @param {Object} targetRect {x, y, width, height}
     * @param {Object} rect {x, y, width, height}
     * @return {Object} A new clipped rect. If rect size are negative, return undefined.
     */
    graphic.clipRectByRect = function (targetRect, rect) {
        var x = mathMax(targetRect.x, rect.x);
        var x2 = mathMin(targetRect.x + targetRect.width, rect.x + rect.width);
        var y = mathMax(targetRect.y, rect.y);
        var y2 = mathMin(targetRect.y + targetRect.height, rect.y + rect.height);

        if (x2 >= x && y2 >= y) {
            return {
                x: x,
                y: y,
                width: x2 - x,
                height: y2 - y
            };
        }
    };

S
sushuang 已提交
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806
    /**
     * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
     * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
     * @param {Object} [rect] {x, y, width, height}
     * @return {module:zrender/Element} Icon path or image element.
     */
    graphic.createIcon = function (iconStr, opt, rect) {
        opt = zrUtil.extend({rectHover: true}, opt);
        var style = opt.style = {strokeNoScale: true};
        rect = rect || {x: -1, y: -1, width: 2, height: 2};

        return iconStr.indexOf('image://') === 0
            ? (
                style.image = iconStr.slice(8),
                zrUtil.defaults(style, rect),
                new graphic.Image(opt)
            )
            : (
                graphic.makePath(
                    iconStr.replace('path://', ''),
                    opt,
                    rect,
                    'center'
                )
            );
    };

807
    return graphic;
O
tweak  
Ovilia 已提交
808
});