-
Notifications
You must be signed in to change notification settings - Fork 379
Expand file tree
/
Copy pathhelpers.canvas.js
More file actions
420 lines (397 loc) · 13 KB
/
Copy pathhelpers.canvas.js
File metadata and controls
420 lines (397 loc) · 13 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
import {addRoundedRectPath, isArray, isNumber, toFont, toPadding, toTRBLCorners, toRadians, PI, TAU, HALF_PI, QUARTER_PI, TWO_THIRDS_PI, RAD_PER_DEG} from 'chart.js/helpers';
import {clampAll, clamp} from './helpers.core';
import {calculateTextAlignment, getSize} from './helpers.options';
const BLANK = ' ';
const widthCache = new Map();
const notRadius = (radius) => isNaN(radius) || radius <= 0;
const fontsKey = (fonts) => fonts.reduce(function(prev, item) {
prev += item.string;
return prev;
}, '');
const getContent = (content, wrappedText) => wrappedText
? wrappedText
: isArray(content)
? content
: [content];
/**
* @typedef { import('chart.js').Point } Point
* @typedef { import('../../types/label').CoreLabelOptions } CoreLabelOptions
* @typedef { import('../../types/options').PointAnnotationOptions } PointAnnotationOptions
*/
/**
* Determine if content is an image or a canvas.
* @param {*} content
* @returns boolean|undefined
* @todo move this function to chart.js helpers
*/
export function isImageOrCanvas(content) {
if (content && typeof content === 'object') {
const type = content.toString();
return (type === '[object HTMLImageElement]' || type === '[object HTMLCanvasElement]');
}
}
/**
* Set the translation on the canvas if the rotation must be applied.
* @param {CanvasRenderingContext2D} ctx - chart canvas context
* @param {Point} point - the point of translation
* @param {number} rotation - rotation (in degrees) to apply
*/
export function translate(ctx, {x, y}, rotation) {
if (rotation) {
ctx.translate(x, y);
ctx.rotate(toRadians(rotation));
ctx.translate(-x, -y);
}
}
/**
* @param {CanvasRenderingContext2D} ctx
* @param {Object} options
* @returns {boolean|undefined}
*/
export function setBorderStyle(ctx, options) {
if (options && options.borderWidth) {
ctx.lineCap = options.borderCapStyle;
ctx.setLineDash(options.borderDash);
ctx.lineDashOffset = options.borderDashOffset;
ctx.lineJoin = options.borderJoinStyle;
ctx.lineWidth = options.borderWidth;
ctx.strokeStyle = options.borderColor;
return true;
}
}
/**
* @param {CanvasRenderingContext2D} ctx
* @param {Object} options
*/
export function setShadowStyle(ctx, options) {
ctx.shadowColor = options.backgroundShadowColor;
ctx.shadowBlur = options.shadowBlur;
ctx.shadowOffsetX = options.shadowOffsetX;
ctx.shadowOffsetY = options.shadowOffsetY;
}
/**
* @param {CanvasRenderingContext2D} ctx
* @param {CoreLabelOptions} options
* @returns {{width: number, height: number}}
*/
export function measureLabelSize(ctx, options) {
const content = options.content;
if (isImageOrCanvas(content)) {
return {
width: getSize(content.width, options.width),
height: getSize(content.height, options.height)
};
}
const optFont = options.font;
const fonts = isArray(optFont) ? optFont.map(f => toFont(f)) : [toFont(optFont)];
const strokeWidth = options.textStrokeWidth;
const lines = isArray(content) ? content : [content];
const mapKey = lines.join() + fontsKey(fonts) + strokeWidth + (ctx._measureText ? '-spriting' : '');
if (!widthCache.has(mapKey)) {
widthCache.set(mapKey, calculateLabelSize(ctx, lines, fonts, strokeWidth));
}
return widthCache.get(mapKey);
}
/**
* @param {CanvasRenderingContext2D} ctx
* @param {{width: number}} properties
* @param {CoreLabelOptions} options
* @returns {{width: number, height: number}}
*/
export function measureWrappedLabelSize(ctx, properties, options) {
const wrappedOptions = wrapLabel(ctx, properties, options);
const result = measureLabelSize(ctx, {
content: wrappedOptions.content,
font: wrappedOptions.font,
textStrokeWidth: options.textStrokeWidth
});
result.wrappedOptions = wrappedOptions;
return result;
}
/**
* @param {CanvasRenderingContext2D} ctx
* @param {{x: number, y: number, width: number, height: number}} rect
* @param {Object} options
*/
export function drawBox(ctx, rect, options) {
const {x, y, width, height} = rect;
ctx.save();
setShadowStyle(ctx, options);
const stroke = setBorderStyle(ctx, options);
ctx.fillStyle = options.backgroundColor;
ctx.beginPath();
addRoundedRectPath(ctx, {
x, y, w: width, h: height,
radius: clampAll(toTRBLCorners(options.borderRadius), 0, Math.min(width, height) / 2)
});
ctx.closePath();
ctx.fill();
if (stroke) {
ctx.shadowColor = options.borderShadowColor;
ctx.stroke();
}
ctx.restore();
}
/**
* @param {CanvasRenderingContext2D} ctx
* @param {{x: number, y: number, width: number, height: number, _wrappedOptions: object|undefined}} rect
* @param {CoreLabelOptions} options
*/
export function drawLabel(ctx, rect, options) {
const content = options.content;
if (isImageOrCanvas(content)) {
ctx.save();
ctx.globalAlpha = getOpacity(options.opacity, content.style.opacity);
ctx.drawImage(content, rect.x, rect.y, rect.width, rect.height);
ctx.restore();
return;
}
const wrapOpt = rect._wrappedOptions || {};
const labels = getContent(content, wrapOpt.content);
const optFont = wrapOpt.font || options.font;
const fonts = isArray(optFont) ? optFont.map(f => toFont(f)) : [toFont(optFont)];
const optColor = wrapOpt.color || options.color;
const colors = isArray(optColor) ? optColor : [optColor];
const x = calculateTextAlignment(rect, options);
const y = rect.y + options.textStrokeWidth / 2;
ctx.save();
ctx.textBaseline = 'middle';
ctx.textAlign = options.textAlign;
if (setTextStrokeStyle(ctx, options)) {
applyLabelDecoration(ctx, {x, y}, labels, fonts);
}
applyLabelContent(ctx, {x, y}, labels, {fonts, colors});
ctx.restore();
}
function setTextStrokeStyle(ctx, options) {
if (options.textStrokeWidth > 0) {
// https://stackoverflow.com/questions/13627111/drawing-text-with-an-outer-stroke-with-html5s-canvas
ctx.lineJoin = 'round';
ctx.miterLimit = 2;
ctx.lineWidth = options.textStrokeWidth;
ctx.strokeStyle = options.textStrokeColor;
return true;
}
}
/**
* @param {CanvasRenderingContext2D} ctx
* @param {{radius: number, options: PointAnnotationOptions}} element
* @param {number} x
* @param {number} y
*/
export function drawPoint(ctx, element, x, y) {
const {radius, options} = element;
const style = options.pointStyle;
const rotation = options.rotation;
let rad = (rotation || 0) * RAD_PER_DEG;
if (isImageOrCanvas(style)) {
ctx.save();
ctx.translate(x, y);
ctx.rotate(rad);
ctx.drawImage(style, -style.width / 2, -style.height / 2, style.width, style.height);
ctx.restore();
return;
}
if (notRadius(radius)) {
return;
}
drawPointStyle(ctx, {x, y, radius, rotation, style, rad});
}
function drawPointStyle(ctx, {x, y, radius, rotation, style, rad}) {
let xOffset, yOffset, size, cornerRadius;
ctx.beginPath();
switch (style) {
// Default includes circle
default:
ctx.arc(x, y, radius, 0, TAU);
ctx.closePath();
break;
case 'triangle':
ctx.moveTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
rad += TWO_THIRDS_PI;
ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
rad += TWO_THIRDS_PI;
ctx.lineTo(x + Math.sin(rad) * radius, y - Math.cos(rad) * radius);
ctx.closePath();
break;
case 'rectRounded':
// NOTE: the rounded rect implementation changed to use `arc` instead of
// `quadraticCurveTo` since it generates better results when rect is
// almost a circle. 0.516 (instead of 0.5) produces results with visually
// closer proportion to the previous impl and it is inscribed in the
// circle with `radius`. For more details, see the following PRs:
// https://github.com/chartjs/Chart.js/issues/5597
// https://github.com/chartjs/Chart.js/issues/5858
cornerRadius = radius * 0.516;
size = radius - cornerRadius;
xOffset = Math.cos(rad + QUARTER_PI) * size;
yOffset = Math.sin(rad + QUARTER_PI) * size;
ctx.arc(x - xOffset, y - yOffset, cornerRadius, rad - PI, rad - HALF_PI);
ctx.arc(x + yOffset, y - xOffset, cornerRadius, rad - HALF_PI, rad);
ctx.arc(x + xOffset, y + yOffset, cornerRadius, rad, rad + HALF_PI);
ctx.arc(x - yOffset, y + xOffset, cornerRadius, rad + HALF_PI, rad + PI);
ctx.closePath();
break;
case 'rect':
if (!rotation) {
size = Math.SQRT1_2 * radius;
ctx.rect(x - size, y - size, 2 * size, 2 * size);
break;
}
rad += QUARTER_PI;
/* falls through */
case 'rectRot':
xOffset = Math.cos(rad) * radius;
yOffset = Math.sin(rad) * radius;
ctx.moveTo(x - xOffset, y - yOffset);
ctx.lineTo(x + yOffset, y - xOffset);
ctx.lineTo(x + xOffset, y + yOffset);
ctx.lineTo(x - yOffset, y + xOffset);
ctx.closePath();
break;
case 'crossRot':
rad += QUARTER_PI;
/* falls through */
case 'cross':
xOffset = Math.cos(rad) * radius;
yOffset = Math.sin(rad) * radius;
ctx.moveTo(x - xOffset, y - yOffset);
ctx.lineTo(x + xOffset, y + yOffset);
ctx.moveTo(x + yOffset, y - xOffset);
ctx.lineTo(x - yOffset, y + xOffset);
break;
case 'star':
xOffset = Math.cos(rad) * radius;
yOffset = Math.sin(rad) * radius;
ctx.moveTo(x - xOffset, y - yOffset);
ctx.lineTo(x + xOffset, y + yOffset);
ctx.moveTo(x + yOffset, y - xOffset);
ctx.lineTo(x - yOffset, y + xOffset);
rad += QUARTER_PI;
xOffset = Math.cos(rad) * radius;
yOffset = Math.sin(rad) * radius;
ctx.moveTo(x - xOffset, y - yOffset);
ctx.lineTo(x + xOffset, y + yOffset);
ctx.moveTo(x + yOffset, y - xOffset);
ctx.lineTo(x - yOffset, y + xOffset);
break;
case 'line':
xOffset = Math.cos(rad) * radius;
yOffset = Math.sin(rad) * radius;
ctx.moveTo(x - xOffset, y - yOffset);
ctx.lineTo(x + xOffset, y + yOffset);
break;
case 'dash':
ctx.moveTo(x, y);
ctx.lineTo(x + Math.cos(rad) * radius, y + Math.sin(rad) * radius);
break;
}
ctx.fill();
}
function calculateLabelSize(ctx, lines, fonts, strokeWidth) {
ctx.save();
const count = lines.length;
let width = 0;
let height = strokeWidth;
for (let i = 0; i < count; i++) {
const font = fonts[Math.min(i, fonts.length - 1)];
ctx.font = font.string;
const text = lines[i];
width = Math.max(width, ctx.measureText(text).width + strokeWidth);
height += font.lineHeight;
}
ctx.restore();
return {width, height};
}
function applyLabelDecoration(ctx, {x, y}, labels, fonts) {
ctx.beginPath();
let lhs = 0;
labels.forEach(function(l, i) {
const f = fonts[Math.min(i, fonts.length - 1)];
const lh = f.lineHeight;
ctx.font = f.string;
ctx.strokeText(l, x, y + lh / 2 + lhs);
lhs += lh;
});
ctx.stroke();
}
function applyLabelContent(ctx, {x, y}, labels, {fonts, colors}) {
let lhs = 0;
labels.forEach(function(l, i) {
const c = colors[Math.min(i, colors.length - 1)];
const f = fonts[Math.min(i, fonts.length - 1)];
const lh = f.lineHeight;
ctx.beginPath();
ctx.font = f.string;
ctx.fillStyle = c;
ctx.fillText(l, x, y + lh / 2 + lhs);
lhs += lh;
ctx.fill();
});
}
function getOpacity(value, elementValue) {
const opacity = isNumber(value) ? value : elementValue;
return isNumber(opacity) ? clamp(opacity, 0, 1) : 1;
}
function wrapLabel(ctx, properties, options) {
const padding = toPadding(options.padding);
const maxWidth = properties.width - padding.left - padding.right - options.borderWidth;
const content = options.content;
const text = isArray(content) ? content : [content];
const optFont = options.font;
const fonts = isArray(optFont) ? optFont : [optFont];
const optColor = options.color;
const colors = isArray(optColor) ? optColor : [optColor];
ctx.save();
const result = scanLabelLines(ctx, text, maxWidth, {fonts, colors});
ctx.restore();
return result;
}
function scanLabelLines(ctx, text, maxWidth, {fonts, colors}) {
const result = {
content: [],
font: [],
color: []
};
text.forEach(function(line, index) {
const normLine = line + '';
const c = colors[Math.min(index, colors.length - 1)];
const f = fonts[Math.min(index, fonts.length - 1)];
const font = toFont(f);
ctx.font = font.string;
const width = ctx.measureText(normLine).width;
if (maxWidth >= width || !normLine.includes(BLANK)) {
result.content.push(normLine);
result.font.push(f);
result.color.push(c);
} else {
const wrappedLine = splitLabel(ctx, normLine, maxWidth);
result.content.push(...wrappedLine);
result.font.push(...wrappedLine.map(() => f));
result.color.push(...wrappedLine.map(() => c));
}
});
return result;
}
function splitLabel(ctx, text, maxWidth) {
const sepaWidth = ctx.measureText(BLANK).width;
const result = [];
const words = text.split(BLANK);
let temp = '';
let current = 0;
for (const w of words) {
const wWidth = ctx.measureText(w).width;
if ((current + wWidth + sepaWidth) <= maxWidth) {
temp += w + BLANK;
current += wWidth + sepaWidth;
} else {
result.push(temp.trim());
temp = w + BLANK;
current = wWidth + sepaWidth;
}
}
if (temp.length) {
result.push(temp.trim());
}
return result;
}