海鸥示例代码
HarmonyOS 5
数学类上架项目解析21-Canvas绑定函数图像
在开发鸿蒙数学计算应用时,需要实现函数图像的可视化功能。要求:
1. 在Canvas上绑制坐标系
2. 根据函数表达式绘制曲线
3. 支持缩放和平移查看
如何用ArkTS在Canvas上绘制数学函数图像?

Canvas绑制函数图像的核心是建立数学坐标系与Canvas像素坐标的映射关系,然后通过采样点连线绘制曲线。
坐标转换:
- 数学坐标 (x, y) → Canvas坐标 (px, py)
- px = (x - xMin) / (xMax - xMin) canvasWidth
- py = canvasHeight - (y - yMin) / (yMax - yMin) canvasHeight
1. 定义数据模型
// 视口范围
interface ViewPort {
xMin: number
xMax: number
yMin: number
yMax: number
}
// 绑制配置
interface PlotConfig {
width: number // Canvas宽度
height: number // Canvas高度
viewport: ViewPort // 视口范围
gridColor: string // 网格颜色
axisColor: string // 坐标轴颜色
curveColor: string // 曲线颜色
curveWidth: number // 曲线宽度
showGrid: boolean // 是否显示网格
samplePoints: number // 采样点数量
}
// 数学函数类型
type MathFunction = (x: number) => number
// 默认配置
const defaultConfig: PlotConfig = {
width: 300,
height: 300,
viewport: { xMin: -10, xMax: 10, yMin: -10, yMax: 10 },
gridColor: '#E0E0E0',
axisColor: '#333333',
curveColor: '#007AFF',
curveWidth: 2,
showGrid: true,
samplePoints: 500
}2. 坐标转换工具
// 坐标转换器
class CoordinateTransformer {
private config: PlotConfig
constructor(config: PlotConfig) {
this.config = config
}
// 数学坐标转Canvas坐标
mathToCanvas(x: number, y: number): { px: number, py: number } {
const { width, height, viewport } = this.config
const { xMin, xMax, yMin, yMax } = viewport
const px = (x - xMin) / (xMax - xMin) width
const py = height - (y - yMin) / (yMax - yMin) height
return { px, py }
}
// Canvas坐标转数学坐标
canvasToMath(px: number, py: number): { x: number, y: number } {
const { width, height, viewport } = this.config
const { xMin, xMax, yMin, yMax } = viewport
const x = px / width (xMax - xMin) + xMin
const y = (height - py) / height (yMax - yMin) + yMin
return { x, y }
}
// 更新配置
updateConfig(config: Partial<PlotConfig>): void {
Object.assign(this.config, config)
}
}3. 函数图像绘制器
// 函数图像绘制器
class FunctionPlotter {
private ctx: CanvasRenderingContext2D
private config: PlotConfig
private transformer: CoordinateTransformer
constructor(ctx: CanvasRenderingContext2D, config: Partial<PlotConfig> = {}) {
this.ctx = ctx
this.config = { ...defaultConfig, ...config }
this.transformer = new CoordinateTransformer(this.config)
}
// 清空画布
clear(): void {
this.ctx.clearRect(0, 0, this.config.width, this.config.height)
this.ctx.fillStyle = '#FFFFFF'
this.ctx.fillRect(0, 0, this.config.width, this.config.height)
}
// 绘制网格
drawGrid(): void {
if (!this.config.showGrid) return
const { width, height, viewport } = this.config
const { xMin, xMax, yMin, yMax } = viewport
this.ctx.strokeStyle = this.config.gridColor
this.ctx.lineWidth = 0.5
// 计算网格间距
const xRange = xMax - xMin
const yRange = yMax - yMin
const xStep = this.calculateGridStep(xRange)
const yStep = this.calculateGridStep(yRange)
// 绘制垂直网格线
for (let x = Math.ceil(xMin / xStep) xStep; x <= xMax; x += xStep) {
const { px } = this.transformer.mathToCanvas(x, 0)
this.ctx.beginPath()
this.ctx.moveTo(px, 0)
this.ctx.lineTo(px, height)
this.ctx.stroke()
}
// 绘制水平网格线
for (let y = Math.ceil(yMin / yStep) yStep; y <= yMax; y += yStep) {
const { py } = this.transformer.mathToCanvas(0, y)
this.ctx.beginPath()
this.ctx.moveTo(0, py)
this.ctx.lineTo(width, py)
this.ctx.stroke()
}
}
// 计算合适的网格间距
private calculateGridStep(range: number): number {
const targetLines = 10
const rawStep = range / targetLines
const magnitude = Math.pow(10, Math.floor(Math.log10(rawStep)))
const normalized = rawStep / magnitude
if (normalized < 2) return magnitude
if (normalized < 5) return 2 magnitude
return 5 magnitude
}
// 绘制坐标轴
drawAxes(): void {
const { width, height, viewport } = this.config
const { xMin, xMax, yMin, yMax } = viewport
this.ctx.strokeStyle = this.config.axisColor
this.ctx.lineWidth = 1.5
// X轴
if (yMin <= 0 && yMax >= 0) {
const { py } = this.transformer.mathToCanvas(0, 0)
this.ctx.beginPath()
this.ctx.moveTo(0, py)
this.ctx.lineTo(width, py)
this.ctx.stroke()
// X轴箭头
this.ctx.beginPath()
this.ctx.moveTo(width - 10, py - 5)
this.ctx.lineTo(width, py)
this.ctx.lineTo(width - 10, py + 5)
this.ctx.stroke()
}
// Y轴
if (xMin <= 0 && xMax >= 0) {
const { px } = this.transformer.mathToCanvas(0, 0)
this.ctx.beginPath()
this.ctx.moveTo(px, height)
this.ctx.lineTo(px, 0)
this.ctx.stroke()
// Y轴箭头
this.ctx.beginPath()
this.ctx.moveTo(px - 5, 10)
this.ctx.lineTo(px, 0)
this.ctx.lineTo(px + 5, 10)
this.ctx.stroke()
}
// 绘制刻度标签
this.drawAxisLabels()
}
// 绘制刻度标签
private drawAxisLabels(): void {
const { viewport } = this.config
const { xMin, xMax, yMin, yMax } = viewport
this.ctx.fillStyle = this.config.axisColor
this.ctx.font = '10px sans-serif'
this.ctx.textAlign = 'center'
this.ctx.textBaseline = 'top'
const xStep = this.calculateGridStep(xMax - xMin)
const yStep = this.calculateGridStep(yMax - yMin)
// X轴刻度
for (let x = Math.ceil(xMin / xStep) xStep; x <= xMax; x += xStep) {
if (Math.abs(x) < 0.0001) continue // 跳过原点
const { px, py } = this.transformer.mathToCanvas(x, 0)
const label = this.formatNumber(x)
this.ctx.fillText(label, px, py + 5)
}
// Y轴刻度
this.ctx.textAlign = 'right'
this.ctx.textBaseline = 'middle'
for (let y = Math.ceil(yMin / yStep) yStep; y <= yMax; y += yStep) {
if (Math.abs(y) < 0.0001) continue // 跳过原点
const { px, py } = this.transformer.mathToCanvas(0, y)
const label = this.formatNumber(y)
this.ctx.fillText(label, px - 5, py)
}
// 原点标签
const origin = this.transformer.mathToCanvas(0, 0)
this.ctx.textAlign = 'right'
this.ctx.textBaseline = 'top'
this.ctx.fillText('O', origin.px - 5, origin.py + 5)
}
// 格式化数字显示
private formatNumber(n: number): string {
if (Math.abs(n) >= 1000 || (Math.abs(n) < 0.01 && n !== 0)) {
return n.toExponential(1)
}
return n.toFixed(Math.abs(n) < 1 ? 2 : 0)
}
// 绘制函数曲线
drawFunction(f: MathFunction, color?: string): void {
const { width, viewport, samplePoints } = this.config
const { xMin, xMax } = viewport
this.ctx.strokeStyle = color || this.config.curveColor
this.ctx.lineWidth = this.config.curveWidth
this.ctx.beginPath()
const step = (xMax - xMin) / samplePoints
let isFirstPoint = true
let lastValidY: number | null = null
for (let i = 0; i <= samplePoints; i++) {
const x = xMin + i step
let y: number
try {
y = f(x)
} catch {
isFirstPoint = true
continue
}
// 跳过无效值
if (!isFinite(y) || isNaN(y)) {
isFirstPoint = true
continue
}
// 检测不连续点(如tan函数的渐近线)
if (lastValidY !== null && Math.abs(y - lastValidY) > (viewport.yMax - viewport.yMin) 0.5) {
isFirstPoint = true
}
const { px, py } = this.transformer.mathToCanvas(x, y)
if (isFirstPoint) {
this.ctx.moveTo(px, py)
isFirstPoint = false
} else {
this.ctx.lineTo(px, py)
}
lastValidY = y
}
this.ctx.stroke()
}
// 绘制多个函数
drawFunctions(functions: Array<{ f: MathFunction, color: string }>): void {
functions.forEach(({ f, color }) => {
this.drawFunction(f, color)
})
}
/
完整绑制(网格+坐标轴+函数)
/
plot(f: MathFunction): void {
this.clear()
this.drawGrid()
this.drawAxes()
this.drawFunction(f)
}
// 更新视口
setViewport(viewport: ViewPort): void {
this.config.viewport = viewport
this.transformer.updateConfig({ viewport })
}
// 缩放
zoom(factor: number, centerX?: number, centerY?: number): void {
const { viewport } = this.config
const cx = centerX ?? (viewport.xMin + viewport.xMax) / 2
const cy = centerY ?? (viewport.yMin + viewport.yMax) / 2
const newXRange = (viewport.xMax - viewport.xMin) / factor
const newYRange = (viewport.yMax - viewport.yMin) / factor
this.setViewport({
xMin: cx - newXRange / 2,
xMax: cx + newXRange / 2,
yMin: cy - newYRange / 2,
yMax: cy + newYRange / 2
})
}
// 平移
pan(dx: number, dy: number): void {
const { viewport } = this.config
this.setViewport({
xMin: viewport.xMin + dx,
xMax: viewport.xMax + dx,
yMin: viewport.yMin + dy,
yMax: viewport.yMax + dy
})
}
}4. 完整UI组件实现
@Entry
@Component
struct FunctionGraphPage {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private ctx: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private plotter: FunctionPlotter | null = null
@State selectedFunction: string = 'sin(x)'
@State canvasWidth: number = 300
@State canvasHeight: number = 300
private functions: Map<string, MathFunction> = new Map([
['sin(x)', (x: number) => Math.sin(x)],
['cos(x)', (x: number) => Math.cos(x)],
['tan(x)', (x: number) => Math.tan(x)],
['x²', (x: number) => x x],
['x³', (x: number) => x x x],
['1/x', (x: number) => 1 / x],
['√x', (x: number) => Math.sqrt(x)],
['eˣ', (x: number) => Math.exp(x)],
['ln(x)', (x: number) => Math.log(x)]
])
build() {
Column() {
Text('函数图像')
.fontSize(24)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 16 })
// 函数选择
Row() {
Text('选择函数:')
Select(Array.from(this.functions.keys()).map(name => ({ value: name })))
.selected(0)
.value(this.selectedFunction)
.onSelect((index: number, value: string) => {
this.selectedFunction = value
this.drawGraph()
})
}
.margin({ bottom: 16 })
// Canvas画布
Canvas(this.ctx)
.width(this.canvasWidth)
.height(this.canvasHeight)
.backgroundColor('#FFFFFF')
.border({ width: 1, color: '#E0E0E0' })
.onReady(() => {
this.initPlotter()
this.drawGraph()
})
// 缩放控制
Row() {
Button('放大')
.onClick(() => {
this.plotter?.zoom(1.5)
this.drawGraph()
})
.margin({ right: 16 })
Button('缩小')
.onClick(() => {
this.plotter?.zoom(0.67)
this.drawGraph()
})
.margin({ right: 16 })
Button('重置')
.onClick(() => {
this.plotter?.setViewport({ xMin: -10, xMax: 10, yMin: -10, yMax: 10 })
this.drawGraph()
})
}
.margin({ top: 16 })
// 平移控制
Row() {
Button('←')
.onClick(() => { this.plotter?.pan(-2, 0); this.drawGraph() })
Button('→')
.onClick(() => { this.plotter?.pan(2, 0); this.drawGraph() })
.margin({ left: 8 })
Button('↑')
.onClick(() => { this.plotter?.pan(0, 2); this.drawGraph() })
.margin({ left: 8 })
Button('↓')
.onClick(() => { this.plotter?.pan(0, -2); this.drawGraph() })
.margin({ left: 8 })
}
.margin({ top: 8 })
}
.width('100%')
.height('100%')
.padding(20)
}
initPlotter(): void {
this.plotter = new FunctionPlotter(this.ctx, {
width: this.canvasWidth,
height: this.canvasHeight,
viewport: { xMin: -10, xMax: 10, yMin: -10, yMax: 10 }
})
}
drawGraph(): void {
if (!this.plotter) return
const f = this.functions.get(this.selectedFunction)
if (f) {
this.plotter.plot(f)
}
}
}5. 使用示例
// 创建绘制器
const plotter = new FunctionPlotter(ctx, {
width: 400,
height: 400,
viewport: { xMin: -5, xMax: 5, yMin: -5, yMax: 5 }
})
// 绘制单个函数
plotter.plot((x) => Math.sin(x))
// 绘制多个函数
plotter.clear()
plotter.drawGrid()
plotter.drawAxes()
plotter.drawFunctions([
{ f: (x) => Math.sin(x), color: '#FF0000' },
{ f: (x) => Math.cos(x), color: '#00FF00' },
{ f: (x) => x x / 5, color: '#0000FF' }
])
// 缩放查看
plotter.zoom(2) // 放大2倍
plotter.plot((x) => Math.sin(x))
// 平移查看
plotter.pan(5, 0) // 向右平移5个单位
plotter.plot((x) => Math.sin(x))总结
使用ArkTS在Canvas上绘制函数图像的关键点:
1. 建立数学坐标系与Canvas像素坐标的转换关系
2. 先绘制网格和坐标轴,再绘制函数曲线
3. 通过采样点连线绘制曲线,采样点越多越平滑
4. 处理函数不连续点(如tan的渐近线)避免错误连线
5. 支持缩放和平移,通过修改视口范围实现
6. 自动计算合适的网格间距和刻度标签
- 为了保障您的信息安全,请勿上传您的敏感个人信息(如您的密码等信息)和您的敏感资产信息(如关键源代码、签名私钥、调试安装包、业务日志等信息),且您需自行承担由此产生的信息泄露等安全风险。
- 如您发布的内容为转载内容,请注明内容来源。
我要提问题
HarmonyOS Canvas clearRect后仍存在之前图像问题如何处理?(API12+)
HarmonyOS 如何用Canvas实现涂鸦和擦除的功能?(API12+)
HarmonyOS 如何实现用Canvas绘制一个圆点(API12+)
HarmonyOS Canvas组件绑定拖动手势绘制路径,总是重复绘制(API12+)
HarmonyOS 能否在一个PixelMap位图上进行绘制,如使用Canvas进行绘制完成后写入位图中 (API12+)
如何实现数学公式渲染
HarmonyOS Canvas组件如何使用Worker线程绘制 (API12+)
HarmonyOS 如何使用Canvas绘制一个汽车仪表盘 (API12+)




































苏公安网备 32011402010933号