Ionic的官网Ionic and Typings,介绍如何在Ionic项目中使用第三方JavaScript库。
example
Ionic3项目中使用ChartJs。
1, 安装ChartJs库
cd /项目的根目录下npm install chart.js --save
2, 全局安装typings
npm install -g typings
3, 搜一下有多少个chart.js的源啦
typings search chart.js
Viewing 2 of 2 NAME SOURCE HOMEPAGE DESCRIPTION VERSIONS UPDATED chart.js npm https://www.npmjs.com/package/chart.js 1 2016-06-15T17:49:20.000Z chart dt https://github.com/nnnick/Chart.js 1 2016-03-16T15:55:26.000Z
4, 安装chart.js
typings install chart.js --save
基本的环境配置到这里搞定了
接下来看一下如何在项目中使用
1, 参考ChartJS的官网,在xxx.html创建一个Chart.
<ion-content padding class="about">
<canvas id="myChart" width="400" height="400"></canvas>
</ion-content>
2, 在xxx.ts中引用Chart,并创建数据。如下
import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import * as ChartJs from 'chart.js'; // 导入chart.js
@Component({
templateUrl: 'build/pages/about/about.html'
})
export class AboutPage {
constructor(private navController:NavController) {
}
ionViewDidEnter() {
var canvas = <HTMLCanvasElement> document.getElementById("myChart");
var ctx = canvas.getContext("2d"); // 这里是关键, 不能写在constructor()中
ChartJs.Line(ctx,{
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
}
}]
}
}
})
}
}