Appearance
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html,
body {
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas')
const context = canvas.getContext('2d')
canvas.style.background = '#ddd'
canvas.width = 800
canvas.height = 800
const AXIS_MARGIN = 40.5
const X_AXIS_START = {
x: AXIS_MARGIN,
y: context.canvas.height - AXIS_MARGIN
}
const X_AXIS_END = {
x: context.canvas.width - AXIS_MARGIN,
y: context.canvas.height - AXIS_MARGIN
}
const Y_AXIS_START = {
x: AXIS_MARGIN,
y: context.canvas.height - AXIS_MARGIN
}
const Y_AXIS_END = {
x: AXIS_MARGIN,
y: AXIS_MARGIN
}
const AXIS_LINE_WIDTH = 1
const AXIS_COLOR = 'black'
const TICK_WIDTH = 8
const TICK_LINE_WIDTH = 0.5
const TICK_COLOR = 'blue'
const X_TICK_SPACING = 10
const Y_TICK_SPACING = 10
const NUM_X_TICK = Math.floor((X_AXIS_END.x - X_AXIS_START.x) / X_TICK_SPACING)
const NUM_Y_TICK = Math.floor((Y_AXIS_START.y - Y_AXIS_END.y) / Y_TICK_SPACING)
const drawAxis = function () {
context.strokeStyle = AXIS_COLOR
context.lineWidth = AXIS_LINE_WIDTH
drawXAxis()
drawYAxis()
context.strokeStyle = TICK_COLOR
context.lineWidth = TICK_LINE_WIDTH
drawXAxisTick()
drawYAxisTick()
}
// X 轴
const drawXAxis = function () {
context.beginPath()
context.moveTo(X_AXIS_START.x, X_AXIS_START.y)
context.lineTo(X_AXIS_END.x, X_AXIS_END.y)
context.stroke()
}
// Y 轴
const drawYAxis = function () {
context.beginPath()
context.moveTo(Y_AXIS_START.x, Y_AXIS_START.y)
context.lineTo(Y_AXIS_END.x, Y_AXIS_END.y)
context.stroke()
}
const drawXAxisTick = function () {
let formattedTickWidth = null
for (let i = X_AXIS_START.x + X_TICK_SPACING, counter = 1; i < X_AXIS_END.x; i += X_TICK_SPACING, counter++) {
context.beginPath()
if (counter % 5 === 0) {
formattedTickWidth = TICK_WIDTH
} else {
formattedTickWidth = TICK_WIDTH / 2
}
context.moveTo(i, X_AXIS_START.y + formattedTickWidth)
context.lineTo(i, X_AXIS_START.y - formattedTickWidth)
context.stroke()
}
}
const drawYAxisTick = function () {
let formattedTickWidth = null
for (let i = Y_AXIS_START.y - Y_TICK_SPACING, counter = 1; i > Y_AXIS_END.y; i -= Y_TICK_SPACING, counter++) {
context.beginPath()
if (counter % 5 === 0) {
formattedTickWidth = TICK_WIDTH
} else {
formattedTickWidth = TICK_WIDTH / 2
}
context.moveTo(Y_AXIS_START.x + formattedTickWidth, i)
context.lineTo(Y_AXIS_START.x - formattedTickWidth, i)
context.stroke()
}
}
drawAxis()
</script>
</body>
</html>