canvas練習棒グラフつくってみる
どういうわけかnoteでコードはれるのね。書きにくい。けどやってみる。
class Setting {
static OFFSET_X = 100;
static OFFSET_Y = 100;
static BASE_HEIGHT = 1;
static BASE_WIDTH = 10;
static MERGIN = 10;
}
class Bar {
constructor(context,startX,startY,height,text) {
this.context = context;
this.startX = startX;
this.startY = startY;
this.height = height;
this.text = text;
}
draw() {
this.context.strokeRect(this.startX, this.startY, Setting.BASE_WIDTH, -this.height);
this.context.fillText(this.text, this.startX+Setting.BASE_WIDTH/4, this.startY+20);
}
}
class Graph{
constructor(context, dataList) {
this.barList = [];
for (let i = 0; i < dataList.length; i++) {
const startX = Setting.OFFSET_X + i*Setting.BASE_WIDTH + i*Setting.MERGIN
const startY = Setting.OFFSET_Y;
const height = Setting.BASE_HEIGHT * dataList[i];
const bar = new Bar(context, startX, startY, height, i);
this.barList.push(bar);
}
}
draw() {
this.barList.forEach(bar => bar.draw())
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Document</title>
</head>
<body>
<canvas id="canvas1">
</canvas>
<script src="./setting.js"></script>
<script src="./bar.js"></script>
<script src="./graph.js"></script>
<script>
(function(){
const canvas = document.getElementById("canvas1");
const context = canvas.getContext("2d");
const dataList= [10,20,30,60,80];
const graph = new Graph(context,dataList);
graph.draw();
})()
</script>
</body>
</html>
元ネタ
https://cartman0.hatenablog.com/entry/2015/07/28/012339
Thank you