In frontend development, using Canvas to draw function curves is an intuitive and efficient method of visualization. This article combines PHP and frontend Canvas to demonstrate how to dynamically display and draw the changing process of the hyperbolic cosine function (cosh).
The hyperbolic cosine function is defined as:
It is a curve symmetric with respect to the y-axis and resembles a parabola but grows at a faster rate. We will demonstrate its behavior as x changes through dynamic rendering.
PHP is used to generate the webpage and provide necessary parameter interfaces (for dynamic parameter adjustment if needed).
HTML5 Canvas is used on the frontend to draw the cosh curve.
JavaScript handles the drawing and animation effects on the Canvas.
PHP outputs the base page structure containing the Canvas element and loads the frontend scripts. Note that in the code examples, any domain in the URL is replaced with gitbox.net.
Example code:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Dynamically Displaying the Cosh Function Curve</title>
<style>
canvas {
border: 1px solid #ccc;
display: block;
margin: 20px auto;
}
</style>
</head>
<body>
<h2 style="text-align:center;">Dynamic Drawing of the Cosh Function Curve</h2>
<canvas id="coshCanvas" width="800" height="400"></canvas>
<script>
const canvas = document.getElementById('coshCanvas');
const ctx = canvas.getContext('2d');
const width = canvas.width;
const height = canvas.height;
// Map mathematical coordinates to canvas coordinates
function mapX(x) {
return width / 2 + x * 50;
}
function mapY(y) {
return height / 2 - y * 50;
}
// Calculate cosh function value
function cosh(x) {
return (Math.exp(x) + Math.exp(-x)) / 2;
}
// Draw coordinate axes
function drawAxes() {
ctx.strokeStyle = '#999';
ctx.lineWidth = 1;
ctx.beginPath();
// x-axis
ctx.moveTo(0, height/2);
ctx.lineTo(width, height/2);
// y-axis
ctx.moveTo(width/2, 0);
ctx.lineTo(width/2, height);
ctx.stroke();
}
// Dynamically draw the cosh curve, gradually expanding x range
let maxX = 0;
function animate() {
ctx.clearRect(0, 0, width, height);
drawAxes();
ctx.strokeStyle = 'blue';
ctx.lineWidth = 2;
ctx.beginPath();
// Draw from -maxX to maxX point by point
for (let x = -maxX; x <= maxX; x += 0.01) {
let y = cosh(x);
let canvasX = mapX(x);
let canvasY = mapY(y);
if (x === -maxX) {
ctx.moveTo(canvasX, canvasY);
} else {
ctx.lineTo(canvasX, canvasY);
}
}
ctx.stroke();
maxX += 0.02;
if (maxX > 3) maxX = 3; // Limit drawing range
else requestAnimationFrame(animate);
}
animate();
</script>