Chart.js/src/elements/element.line.js
2019-11-12 19:18:58 -05:00

120 lines
3.0 KiB
JavaScript

'use strict';
const defaults = require('../core/core.defaults');
const Element = require('../core/core.element');
const helpers = require('../helpers/index');
const valueOrDefault = helpers.valueOrDefault;
const defaultColor = defaults.global.defaultColor;
defaults._set('global', {
elements: {
line: {
tension: 0.4,
backgroundColor: defaultColor,
borderWidth: 3,
borderColor: defaultColor,
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
capBezierPoints: true,
fill: true, // do we fill in the area between the line and its base axis
}
}
});
class Line extends Element {
constructor(props) {
super(props);
}
draw() {
var me = this;
var vm = me._view;
var ctx = me._ctx;
var spanGaps = vm.spanGaps;
var points = me._children;
var globalDefaults = defaults.global;
var globalOptionLineElements = globalDefaults.elements.line;
var lastDrawnIndex = -1;
var closePath = me._loop;
var index, previous, currentVM;
if (!points.length) {
return;
}
if (me._loop) {
points = points.slice(); // clone array
for (index = 0; index < points.length; ++index) {
previous = points[Math.max(0, index - 1)];
// If the line has an open path, shift the point array
if (!points[index]._view.skip && previous._view.skip) {
points = points.slice(index).concat(points.slice(0, index));
closePath = spanGaps;
break;
}
}
// If the line has a close path, add the first point again
if (closePath) {
points.push(points[0]);
}
}
ctx.save();
// Stroke Line Options
ctx.lineCap = vm.borderCapStyle || globalOptionLineElements.borderCapStyle;
// IE 9 and 10 do not support line dash
if (ctx.setLineDash) {
ctx.setLineDash(vm.borderDash || globalOptionLineElements.borderDash);
}
ctx.lineDashOffset = valueOrDefault(vm.borderDashOffset, globalOptionLineElements.borderDashOffset);
ctx.lineJoin = vm.borderJoinStyle || globalOptionLineElements.borderJoinStyle;
ctx.lineWidth = valueOrDefault(vm.borderWidth, globalOptionLineElements.borderWidth);
ctx.strokeStyle = vm.borderColor || globalDefaults.defaultColor;
// Stroke Line
ctx.beginPath();
// First point moves to its starting position no matter what
currentVM = points[0]._view;
if (!currentVM.skip) {
ctx.moveTo(currentVM.x, currentVM.y);
lastDrawnIndex = 0;
}
for (index = 1; index < points.length; ++index) {
currentVM = points[index]._view;
previous = lastDrawnIndex === -1 ? points[index - 1] : points[lastDrawnIndex];
if (!currentVM.skip) {
if ((lastDrawnIndex !== (index - 1) && !spanGaps) || lastDrawnIndex === -1) {
// There was a gap and this is the first point after the gap
ctx.moveTo(currentVM.x, currentVM.y);
} else {
// Line to next point
helpers.canvas.lineTo(ctx, previous._view, currentVM);
}
lastDrawnIndex = index;
}
}
if (closePath) {
ctx.closePath();
}
ctx.stroke();
ctx.restore();
}
}
Line.prototype._type = 'line';
module.exports = Line;