diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index 301aad415..6d0c9e417 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -165,6 +165,7 @@ module.exports = { 'label/image', 'label/innerChart', 'label/lowerUpper', + 'label/autoscaling' ] }, { diff --git a/docs/samples/label/autoscaling.md b/docs/samples/label/autoscaling.md new file mode 100644 index 000000000..6e52278c3 --- /dev/null +++ b/docs/samples/label/autoscaling.md @@ -0,0 +1,93 @@ +# Auto scaling + + + +```js chart-editor +// +const uniqueId = new Date().getTime(); + +const DATA_COUNT = 12; +const MIN = 0; +const MAX = 100; + +const numberCfg = {count: DATA_COUNT, min: MIN, max: MAX}; + +const data = { + labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + datasets: [{ + data: Utils.numbers(numberCfg) + }] +}; +// + +// +const annotation = { + type: 'label', + backgroundColor: 'whiteSmoke', + borderColor: 'lightGray', + borderRadius: 6, + content: ['Annotation', 'to resize'], + drawTime: 'afterDraw', + borderWidth: (ctx) => autoScaling(ctx, 'borderWidth', 2), + font: (ctx) => autoScaling(ctx, 'font', 48), + padding: (ctx) => autoScaling(ctx, 'padding', 6), +}; +// + +/* */ +const config = { + type: 'line', + data, + options: { + _sampleId: uniqueId, + plugins: { + annotation: { + annotations: { + annotation + } + } + } + } +}; +/* */ + +// +function autoScaling(ctx, option, origValue) { + const {chart} = ctx; + const {width, height} = chart.chartArea; + const hypo = Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2)); + let size, value; + if (!ctx.size) { + ctx.size = size = hypo; + value = origValue; + } else { + size = ctx.size; + value = hypo / size * origValue; + } + if (option === 'font') { + return {size: value}; + } + return value; +} +// + +// +let originalArea; +document.getElementById('update').addEventListener('input', update); + +function update() { + const ratio = +document.querySelector('input[type=range]').value / 100; + const chart = Object.values(Chart.instances).find(c => c.options._sampleId === uniqueId); + if (!originalArea) { + originalArea = chart.chartArea; + } + const w = originalArea.width * ratio; + const h = originalArea.height * ratio; + chart.resize(w, h); +} +// + +module.exports = { + config: config +}; +```