'charts.js 차트'에 해당되는 글 1건

# [charts.js]  intersection 이해하기 

   - charts.js의 제공하는 샘플 코드가 잘되어있어서 주석을 넣었습니다.

   - 아래의 jsffidle 화면을 통해서 비교해서 모드와 intersection을 선택하여 사용하시면 좋을것 같습니다.


 

 

# intersection 사용법 

options: {
	responsive: true,
	title: {
		display: true,
		text: 'Mode: ' + mode + ', intersect = ' + intersect
	},
	tooltips: {
        // 툴팁을 표현하는 방법
        // index, dataset, point, nearest(defalut), x, y
		mode: mode,
        // 툴팁을 표현할 때, 근처일때 표현할 것인가 아닌가
        // true(defalut), false
		intersect: intersect,
	},
	hover: {
		mode: mode,
		intersect: intersect
	},
}

 # intersection 사용한 화면

    - mode와 interesection의 사용법에 따라서 툴팁의 표현이 다릅니다.


 # 전체 테스트 코드

( # charts.js에서 utils.js는 cdn으로 제공하지 않아서 같이 들어가 있습니다. 이점 참고하세요.)

더보기

<!doctype html>

<html>

 

<head>

    <title>Tooltip Interaction Modes</title>

    <!-- <script src="../../dist/chart.min.js"></script> -->

    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js" integrity="sha512-QEiC894KVkN9Tsoi6+mKf8HaCLJvyA6QIRzY5KrfINXYuP9NxdIkRQhGq3BZi0J4I7V5SidGM3XUQ5wFiMDuWg==" crossorigin="anonymous"></script>

    <!-- <script src="../../utils.js"></script> -->

 

<style>

        canvas {

            -moz-user-selectnone;

            -webkit-user-selectnone;

            -ms-user-selectnone;

        }

 

        .chart-container {

            width400px;

            margin-left10px;

            margin-right10px;

            margin-bottom10px;

            border : 1px solid black;

        }

 

        .container {

            displayflex;

            flex-directionrow;

            flex-wrapwrap;

            justify-contentcenter;

        }

    </style>

</head>

 

<body>

    <div class="container"> </div>

    <script>

        var charts = [];

 

        // 차트 생성하기

        function createConfig(modeintersect) {

            return {

                // 차트 타입

                type: 'line',

                // 데이터셋 

                data: {

                    labels: ['January''February''March''April''May''June''July'],

                    datasets: [{

                        label: 'My First dataset',

                        borderColor: window.chartColors.red,

                        backgroundColor: window.chartColors.red,

                        data: [10304628500],

                        fill: false,

                    }, {

                        label: 'My Second dataset',

                        borderColor: window.chartColors.blue,

                        backgroundColor: window.chartColors.blue,

                        data: [7494613253022],

                        fill: false,

                    }]

                },

                // 옵션

                options: {

                    responsive: true,

                    title: {

                        display: true,

                        text: 'Mode: ' + mode + ', intersect = ' + intersect

                    },

                    tooltips: {

                        mode: mode,

                        intersect: intersect,

                    },

                    hover: {

                        mode: mode,

                        intersect: intersect

                    },

                }

            };

        }

 

        window.onload = function () {

            var container = document.querySelector('.container');

            // mode : defalut 'nearest' (툴팁에 표시되는 요소를 설정)

            // intersect : defalut true || false (마우스 위치가 차트의 항목과 교차할 때 만 호보)

            // axis : 

            // animationDuration : 호버 스타일 변경을 애니메이션하는 데 걸리는 시간 (밀리 초)

            [{

                mode: 'index',

                intersect: true,

                animationDuration: 100

            }, {

                mode: 'index',

                intersect: false,

                animationDuration: 300

            }, {

                mode: 'dataset',

                intersect: true,

                animationDuration: 100

            }, {

                mode: 'dataset',

                intersect: false,

                animationDuration: 300

            }, {

                mode: 'point',

                intersect: true,

                animationDuration: 100

            }, {

                mode: 'point',

                intersect: false,

                animationDuration: 300

            }, {

                mode: 'nearest',

                intersect: true,

                animationDuration: 100

            }, {

                mode: 'nearest',

                intersect: false,

                animationDuration: 300

            }, {

                mode: 'x',

                intersect: true,

                animationDuration: 100

            }, {

                mode: 'x',

                intersect: false,

                animationDuration: 300

            }, {

                mode: 'y',

                intersect: true,

                animationDuration: 100

            }, {

                mode: 'y',

                intersect: false,

                animationDuration: 300

            }].forEach(function (details) {

                console.log('details'details);

                // div 생성. <div class='chart-container'> </div> 

                var div = document.createElement('div');

                div.classList.add('chart-container');

 

                // canvas 생성.

                var canvas = document.createElement('canvas');

                div.appendChild(canvas);

                container.appendChild(div);

 

                // 2d 렌더링 컨텍스트를 나타내는 CanvasRenderingContext2D 객체를 생성하게 합니다.

                var ctx = canvas.getContext('2d');

                var config = createConfig(details.modedetails.intersect);

                charts.push(new Chart(ctxconfig));

            });

        };

    </script>

 

    <script>

        // charts.js에서 제공하는 utils.js 

        'use strict';

 

window.chartColors = {

    red: 'rgb(255, 99, 132)',

    orange: 'rgb(255, 159, 64)',

    yellow: 'rgb(255, 205, 86)',

    green: 'rgb(75, 192, 192)',

    blue: 'rgb(54, 162, 235)',

    purple: 'rgb(153, 102, 255)',

    grey: 'rgb(201, 203, 207)'

};

 

(function(global) {

    var MONTHS = [

        'January',

        'February',

        'March',

        'April',

        'May',

        'June',

        'July',

        'August',

        'September',

        'October',

        'November',

        'December'

    ];

 

    var COLORS = [

        '#4dc9f6',

        '#f67019',

        '#f53794',

        '#537bc4',

        '#acc236',

        '#166a8f',

        '#00a950',

        '#58595b',

        '#8549ba'

    ];

 

    var Samples = global.Samples || (global.Samples = {});

    var Color = Chart.helpers.color;

 

    function applyDefaultNumbers(config) {

        var cfg = config || {};

        cfg.min = cfg.min || 0;

        cfg.max = cfg.max || 1;

        cfg.from = cfg.from || [];

        cfg.count = cfg.count || 8;

        cfg.decimals = cfg.decimals || 8;

        cfg.continuity = cfg.continuity || 1;

 

        return cfg;

    }

 

    Samples.utils = {

        // Adapted from http://indiegamr.com/generate-repeatable-random-numbers-in-js/

        srand: function(seed) {

            this._seed = seed;

        },

 

        rand: function(minmax) {

            var seed = this._seed;

            min = min === undefined ? 0 : min;

            max = max === undefined ? 1 : max;

            this._seed = (seed * 9301 + 49297) % 233280;

            return min + (this._seed / 233280) * (max - min);

        },

 

        numbers: function(config) {

            var cfg = applyDefaultNumbers(config);

            var dfactor = Math.pow(10cfg.decimals) || 0;

            var data = [];

            var ivalue;

 

            for (i = 0i < cfg.count; ++i) {

                value = (cfg.from[i] || 0) + this.rand(cfg.mincfg.max);

                if (this.rand() <= cfg.continuity) {

                    data.push(Math.round(dfactor * value) / dfactor);

                } else {

                    data.push(null);

                }

            }

 

            return data;

        },

 

        labels: function(config) {

            var cfg = config || {};

            var min = cfg.min || 0;

            var max = cfg.max || 100;

            var count = cfg.count || 8;

            var step = (max - min) / count;

            var decimals = cfg.decimals || 8;

            var dfactor = Math.pow(10decimals) || 0;

            var prefix = cfg.prefix || '';

            var values = [];

            var i;

 

            for (i = mini < maxi += step) {

                values.push(prefix + Math.round(dfactor * i) / dfactor);

            }

 

            return values;

        },

 

        months: function(config) {

            var cfg = config || {};

            var count = cfg.count || 12;

            var section = cfg.section;

            var values = [];

            var ivalue;

 

            for (i = 0i < count; ++i) {

                value = MONTHS[Math.ceil(i) % 12];

                values.push(value.substring(0section));

            }

 

            return values;

        },

 

        color: function(index) {

            return COLORS[index % COLORS.length];

        },

 

        transparentize: function(coloropacity) {

            var alpha = opacity === undefined ? 0.5 : 1 - opacity;

            return Color(color).alpha(alpha).rgbString();

        }

    };

 

    // DEPRECATED

    window.randomScalingFactor = function() {

        return Math.round(Samples.utils.rand(-100100));

    };

 

    // INITIALIZATION

 

    Samples.utils.srand(Date.now());

 

    // Google Analytics

    /* eslint-disable */

    if (document.location.hostname.match(/^(www\.)?chartjs\.org$/)) {

        (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){

        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)

        })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

        ga('create''UA-28909194-3''auto');

        ga('send''pageview');

    }

    /* eslint-enable */

 

}(this));

 

    </script>

</body>

 

</html>

블로그 이미지

미나미나미

,