막대그래프
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script>
const canvas = document.getElementById('canvas');
const pen = canvas.getContext('2d');
const canvasWidth = canvas.getAttribute('width');
const canvasHeight = canvas.getAttribute('height');
const scaleFactorX = 50;
const scaleFactorY = 10;
const factorWidth = canvasWidth / scaleFactorX;
const factorHeight = canvasHeight / scaleFactorY;
const factorDotX = 1 / scaleFactorX;
const factorDotY = 1 / scaleFactorY;
const print1 = (x,y) => {
pen.fillRect(x,y,1,1);
}
const printCross = (xW,yH) => {
for(let x=10; x<=xW; x++){
print1(x,yH-10);
}
for(let y=0; y<=yH-10; y++){
print1(xW-490,y)
}
}
printCross(canvasWidth, canvasHeight);
const print2 = (x,y) => {
pen.fillRect((x*scaleFactorX) + (canvasWidth-490), (canvasHeight-10) - (y*scaleFactorY), 1, 1)
}
const printScaleFactor = (x,y) => {
for(let x=1; x<factorWidth; x++){
for(let y=-10; y<10; y++){
pen.fillRect(scaleFactorX*x + (canvasWidth-490), (canvasHeight-10) - y , 1, 1);
}
}
for(let y=1; y<factorHeight; y++){
for(let x=-10; x<10; x++){
pen.fillRect( x + (canvasWidth-490) , (canvasHeight-10) - scaleFactorY*y, 1, 1);
}
}
}
printScaleFactor();
let x1 = 1; // x1과 x2의 간격이 넓을 수록 두꺼운 막대그래프가됨
let x2 = 2;
let y1 = [20,20,49,25];
const squarePrin = (x1,y1,x2,y2) => {
// 막대그래프 지붕
for(let x=x1; x<x2; x=x+factorDotX){
print2(x, y1);
}
// 막대그래프 양쪽 수직선
for(let y=y2; y<y1; y=y+factorDotY){
print2(x1, y);
print2(x2, y);
}
}
for(let i=0; i<y1.length; i++){ //0,1,2,3
squarePrin(x1, y1[i], x2, 0);
x1 = x1 + 2; // 막대 그래프 사이에 간격을 두기 위해 +2
x2 = x2 + 2;
}
</script>
</body>
반응형
'JAVASCRIPT' 카테고리의 다른 글
JAVASCRIPT ) 전치행렬 (0) | 2024.08.26 |
---|---|
JAVASCRIPT ) 부울행렬의 연산 (0) | 2024.08.26 |
JAVASCRIPT ) 문제 - 배열의 값 뒤집기 (0) | 2024.08.13 |
JAVASCRIPT ) Math.random() 공식 (0) | 2024.08.13 |
JAVASCRIPT ) 이터레이션과 for of문 (0) | 2024.08.09 |