Preface

The project needs to use chart.js plug-in unit , Because the project is using angular Development , So my first step is to put chart.js Transform into angular Components to use .

This project code can be in github Upload and download : project git Address

angular reform

1、 build angular Project steps are omitted , You can check by yourself ng Official documents

2、 Create a chart-js The components of

ng g c chart-js

chart-js.component.html

<div style="display: block; height: 100%">
<canvas #canvas></canvas>
</div>

chart-js.component.ts

import {
Component,
OnInit,
ViewChild,
ElementRef,
AfterViewInit,
Input,
OnChanges,
SimpleChanges,
OnDestroy
} from "@angular/core";
import "chart.js"; declare var window: any;
@Component({
selector: 'chart-js',
templateUrl: './chart-js.component.html',
styleUrls: ['./chart-js.component.css']
})
export class ChartJsComponent implements OnInit, AfterViewInit, OnChanges, OnDestroy { @ViewChild("canvas") canvas: ElementRef; @Input() config; private chart; constructor() { } ngOnInit() {
}
// After the subcomponents are loaded , Render icons
ngAfterViewInit() {
this.render();
}
// Rendering the chart
render() {
this.chart = new window.Chart(
this.canvas.nativeElement.getContext("2d"),
this.config
);
this.chart.height = "100%";
}
// Judge Input Parameters config Change or not , If it changes , Trigger update drawing
ngOnChanges({ config }: SimpleChanges) {
if (config && !config.isFirstChange()) {
this.destroyChart();
this.render();
}
}
// The destruction chart
ngOnDestroy() {
this.destroyChart();
}
// The destruction chart The main body
destroyChart() {
if (this.chart) {
this.chart.destroy();
this.chart = undefined;
}
}
}

Okay angular This is how the component is transformed , Next, let's look at how to call

// html
<div style="width:50%;margin:0 auto;">
<chart-js [config]="config"></chart-js>
</div> // ts
// A simple configuration , The meaning of configuration will be explained in detail later
this.config = {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
},
onHover(event, elements) {
console.log(event,elements);
},
}
}

Let's see the effect :

Configuration details

Please refer to the following link for specific configuration , Very comprehensive

Chart.js Chinese document

Configure a composite chart

You can often see that a data table contains several ways of presentation. See the figure for details :



There are both bar charts and line charts . How to configure things like this ?

Only need dataset Add a new data type and make corresponding type that will do , As follows

 datasets: [
{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
},
{
type: "line", // Change this dataset type to line chart
label: "Line Dataset",
data: [3, 5, 7, 16]
}
]

See the full configuration code

chart.js Plug in writing

Plug in extensions are divided into global plug-ins and inline plug-ins

【 Inline plug-ins 】

Plug ins can also be configured directly in the chart plug-in ( The inline plug-in ) In the definition of

var chart = new Chart(ctx, {
plugins: [
{
beforeInit: function(chart, options) {
//..
}
}
]
});

【 Global plug-ins 】

Plug ins can be registered globally , Apply to all charts ( The global plug-in )

Chart.pluginService.register({
// plugin implementation
});

【 Write a plug-in 】

Let's review the chart we drew above

If the product tells us at this time , Want to add a background color to this chart , And the background color can be set .

Let's turn to the column / Bar chart (Bar) See the configuration here , Found no configuration item , Only for each column / Bar fill colors . It doesn't fill the entire background with color

What do I do ? Write plug-ins .

Check the document and find that the plug-in provides some hook functions for us :

So let's start writing plug-ins formally

 beforeDraw: function(chartInstance) {
// chartInstance === Canvas example // First, let's get the configuration table , See if it's configured chartAreaBackground, If not configured, do not execute
if (!chartInstance.options.chartAreaBackground) return;
var ctx = chartInstance.chart.ctx; // Get canvas context
var chartArea = chartInstance.chartArea; // Canvas area
var left = chartArea.left;
var right = chartArea.right;
var yOptions = chartInstance.scales["y-axis-0"];
var yAxesTop = yOptions.paddingTop;
var yAxesBottom = yOptions.paddingBottom;
var top = chartArea.top + yAxesTop;
var bottom = chartArea.bottom - yAxesBottom;
var width = right - left; // Get the width of the canvas
var height = bottom - top; // Get the height of the canvas
ctx.fillStyle = chartInstance.options.chartAreaBackground; // Get the background color
ctx.fillRect(left, top, width, height); // Hold the fill
}

If the location of the area is not clear, you can see the following label :

The plug-in is ready . How to use it ?

Through judgment in the plug-in chartInstance.options.chartAreaBackground Is this configured . So obviously , We can just configure this

options:{
chartAreaBackground:'#f5f5f5'
}

Let's see the effect :



The gray background color has appeared . We have successfully configured the inline plug-in .

【 Transform the above plug-in into a global plug-in 】

New file chart-plugin.ts

import * as Chart from "chart.js";
const drawBgColorFactory = function (Chart) {
const drawBgColor = {
beforeDraw: function(chartInstance) {
// chartInstance === Canvas example
console.log(chartInstance);
// First, let's get the configuration table , See if it's configured chartAreaBackground, If not configured, do not execute
if (!chartInstance.options.chartAreaBackground) return;
var ctx = chartInstance.chart.ctx; // Get canvas context
var chartArea = chartInstance.chartArea; // Canvas area
var left = chartArea.left;
var right = chartArea.right;
var yOptions = chartInstance.scales["y-axis-0"];
var yAxesTop = yOptions.paddingTop;
var yAxesBottom = yOptions.paddingBottom;
var top = chartArea.top + yAxesTop;
var bottom = chartArea.bottom - yAxesBottom;
var width = right - left; // Get the width of the canvas
var height = bottom - top; // Get the height of the canvas
ctx.fillStyle = chartInstance.options.chartAreaBackground; // Get the background color
ctx.fillRect(left, top, width, height); // Hold the fill
}
}; Chart.pluginService.register(drawBgColor);
}; drawBgColorFactory(Chart);

In this way, we successfully registered in the global

Summary

So far, the global plug-in , We have all implemented local plug-ins , If you want to implement more complex plug-ins , You need to learn more deeply in the project chart.js plug-in unit

chart.js angular Component encapsulation (ng6)、 Actual combat configuration 、 More articles about plug-ins

  1. js Log component encapsulation

    js The logging component ~~ 1 function Logger(level) { if (!(this instanceof Logger)) { return new Logger(); } var ERRO ...

  2. Vue.js Custom component encapsulation record —— Based on the secondary encapsulation of existing controls ( Take the timer as an example )

    In the process of developing an examination system , There is a need for : Make a countdown control to display on the test paper page . This paper records such a process . The early stage of the work For this requirement , Naturally, I think about whether there are ready-made components that can be used directly ( In line with ...

  3. 04.ElementUI Source code learning : Component encapsulation 、 Description of the preparation and release of documents

    0x00. Preface The book follows . The project goes through a series of configurations , The development scaffolding has been set up . Next, start wrapping custom components . And based on markdown File generation documents and demonstration cases . The code of the following articles will be based on the length , Carry on the part without affecting the understanding ...

  4. calendar.js( Calendar component encapsulation )

    I have nothing to do recently , I think about doing my own personal project , I also want to say that I can use some of the more popular ones mvvm Frame to do , So we chose such a technology stack vue2.0+vue-router+vuex+webpack To do it , It's also a lot to do ...

  5. vue2.0 project calendar.js( Calendar component encapsulation )

    I have nothing to do recently , I think about doing my own personal project , I also want to say that I can use some of the more popular ones mvvm Frame to do , So we chose such a technology stack vue2.0+vue-router+vuex+webpack To do it , It's also a lot to do ...

  6. vue.js table Component encapsulation

    table Components and The paging component comes from iview, Here I do a package again according to the company's business , Use slot Distribute content , It can be placed at will input Input box and button Button , Reuse props Passing parameters to subcomponents , Use em ...

  7. Angular Instruction encapsulation jQuery Date time plug in datetimepicker Implement two-way binding

    It's like a sow on holiday . 00. The chaotic frontier Angular1.x It's really a framework with high learning costs , At the beginning of the internship , The front end doesn't know anything , The foreman said Angular, We can only learn from them . before this , The front end is big ...

  8. Hapi+MySql Project actual combat configuration plug-in - Load file render master ( 3、 ... and )

    Add plug-ins Generally in other node Within the framework of , We install the plug-in directly require(' plug-in unit ') You can use it properly , But in Hapi Next time we have to Server.register() Method , To use the plug-in properly . for instance : serv ...

  9. Native JS Object oriented idea encapsulates the carousel diagram component

    Native JS Object oriented idea encapsulates the carousel diagram component In the front-end page development process , Carousel effects are very common on the page , So I want to encapsulate my own original JS The carousel component of . With this demand, we begin to prepare , The goal of the code, of course, is simplicity , The functions of the carousel chart ...

Random recommendation

  1. php The string is assigned to js The pit of

    A long time ago, it was quite a pit , Today I met again , Make a note of , So as not to go into the pit again . hold php Assign values to the view When the layer , If you don't render directly to the page , It's assigned to variables . If the character has a carriage return or a line feed, there will be a problem . Example : <?ph ...

  2. SQL Advanced query ——50 Query ( With answers )

    - A topic involves 50 individual Sql sentence  --( The following table shows the structure of , Create your own tables in the database . And add the corresponding data , The data should be comprehensive . among Student In the table ,SId For the students ID) ----------------- ...

  3. iOS - UIColor

    Preface NS_CLASS_AVAILABLE_IOS(2_0) @interface UIColor : NSObject <NSSecureCoding, NSCopying> @avai ...

  4. eclipse see rt.jar Source code

    Source location : %JAVA_HOME%/src.zip step1: step2: step3:

  5. [Arduino] Two ways to separate text into arrays with commas

    Here's today's exercise using commas to split character arrays / A string of 2 Two examples and methods " 1. adopt indexOf function /* *Splitsplit sketch *split a comma-separated st ...

  6. Shahu King | use Scipy Realization K-means clustering algorithm

    Shahu King | use Scipy Realization K-means clustering algorithm use Scipy Realization K-means clustering algorithm

  7. JS firebug Tips

    In fact, the development and progress of the front end is inseparable from the support of the browser , And for developers , The best browser support , Is for debug Good support for , Even in some projects that might be taken over , Front-end debug It can even solve a lot of problems -- Don't say the , It's all tears ! still ...

  8. by Python Add Chinese keyword

    Shit coffee 2 Months ago Original address : https://zhuanlan.zhihu.com/p/31159526 swizl/cnpython 1. Most grammar , You can add synonymous Chinese as follows token The first 1 Step . ...

  9. [ turn ]C++ Assignment operators overload functions (operator=)

    Write it at the front : About C++ The assignment operator overloads the function (operator=), There are many introductions on the Internet and various teaching materials , But unfortunately , Most of the contents are similar and incomplete . In the face of this situation , On the basis of integrating various resources and integrating personal understanding , Sort out a more ...

  10. Unused Method( Methods that are no longer used )——Dead Code( Death code )

        List of articles :      Use Fortify Static analysis of code ( Series articles ) Unused Method( Methods that are no longer used )     Example :  private bool checkLevel(strin ...