Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
1013 lines (911 loc) · 36 KB
/
Copy pathindex.html
File metadata and controls
1013 lines (911 loc) · 36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>函数图像绘制器</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
background: #f5f7fa;
color: #333;
padding: 20px;
}
.container {
max-width: 1000px;
margin: 0 auto;
}
h1 {
text-align: center;
margin-bottom: 24px;
color: #2c3e50;
}
.panel {
background: white;
border-radius: 12px;
padding: 20px;
box-shadow: 0 2px 12px rgba(0,0,0,0.08);
margin-bottom: 20px;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 16px;
align-items: flex-end;
}
.control-group {
display: flex;
flex-direction: column;
gap: 6px;
}
label {
font-size: 14px;
color: #666;
font-weight: 500;
}
input[type="text"], input[type="number"] {
padding: 10px 14px;
border: 1px solid #ddd;
border-radius: 8px;
font-size: 15px;
outline: none;
transition: border-color 0.2s;
}
input[type="text"]:focus, input[type="number"]:focus {
border-color: #3498db;
}
#functionInput {
width: 260px;
}
.range-input {
width: 90px;
}
button {
padding: 10px 24px;
background: #3498db;
color: white;
border: none;
border-radius: 8px;
font-size: 15px;
cursor: pointer;
transition: background 0.2s;
}
button:hover {
background: #2980b9;
}
.zoom-btn {
padding: 10px 14px;
font-size: 18px;
font-weight: bold;
line-height: 1;
}
#canvas {
width: 100%;
height: 500px;
border-radius: 8px;
background: #fafbfc;
cursor: grab;
user-select: none;
-webkit-user-select: none;
}
#canvas:active {
cursor: grabbing;
}
.hint {
font-size: 13px;
color: #888;
margin-top: 12px;
line-height: 1.6;
}
.hint code {
background: #f0f4f8;
padding: 2px 6px;
border-radius: 4px;
color: #e74c3c;
}
.info {
display: flex;
gap: 24px;
margin-top: 16px;
flex-wrap: wrap;
font-size: 15px;
}
.info-item {
background: #f0f4f8;
padding: 10px 16px;
border-radius: 8px;
}
.info-item span {
color: #666;
}
.info-item strong {
color: #2c3e50;
margin-left: 6px;
}
#errorMsg {
color: #e74c3c;
margin-top: 10px;
font-size: 14px;
min-height: 20px;
}
.example-btn {
padding: 6px 12px;
background: #ecf0f1;
color: #555;
border-radius: 16px;
font-size: 13px;
cursor: pointer;
transition: background 0.2s;
}
.example-btn:hover {
background: #d5dbdb;
}
.examples-row {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
margin-top: 10px;
}
.example-label {
font-size: 13px;
color: #888;
min-width: 60px;
}
.point-result {
margin-top: 14px;
padding: 12px 16px;
background: #f0f4f8;
border-radius: 8px;
font-size: 14px;
line-height: 1.8;
min-height: 44px;
}
.point-result strong {
color: #2c3e50;
}
.checkbox-group {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 10px;
}
.checkbox-group input[type="checkbox"] {
width: 18px;
height: 18px;
cursor: pointer;
}
.checkbox-group label {
cursor: pointer;
margin: 0;
}
.legend {
display: flex;
gap: 20px;
margin-top: 12px;
font-size: 14px;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.legend-color {
width: 24px;
height: 3px;
border-radius: 2px;
}
</style>
</head>
<body>
<div class="container">
<h1>📈 函数图像绘制器</h1>
<div class="panel">
<div class="controls">
<div class="control-group">
<label for="functionInput">函数 f(x) =</label>
<input type="text" id="functionInput" value="x^2" placeholder="例如: sin(x) + x^2">
</div>
<div class="control-group checkbox-group">
<label for="showDerivative">显示导函数 f'(x)</label>
<input type="checkbox" id="showDerivative">
</div>
<button id="plotBtn">绘制图像</button>
<button id="clearBtn">清除</button>
<button id="zoomInBtn" class="zoom-btn" title="放大">+</button>
<button id="zoomOutBtn" class="zoom-btn" title="缩小">−</button>
</div>
<div class="examples-row">
<span class="example-label">幂函数</span>
<span class="example-btn" data-fn="x^2">x²</span>
<span class="example-btn" data-fn="x^3">x³</span>
<span class="example-btn" data-fn="x^4">x⁴</span>
<span class="example-btn" data-fn="sqrt(x)">√x</span>
<span class="example-btn" data-fn="1/x">1/x</span>
<span class="example-btn" data-fn="1/x^2">1/x²</span>
</div>
<div class="examples-row">
<span class="example-label">三角函数</span>
<span class="example-btn" data-fn="sin(x)">sin(x)</span>
<span class="example-btn" data-fn="cos(x)">cos(x)</span>
<span class="example-btn" data-fn="tan(x)">tan(x)</span>
<span class="example-btn" data-fn="sin(2*x)">sin(2x)</span>
<span class="example-btn" data-fn="cos(2*x)">cos(2x)</span>
<span class="example-btn" data-fn="1/tan(x)">cot(x)</span>
</div>
<div class="examples-row">
<span class="example-label">指数/对数</span>
<span class="example-btn" data-fn="e^x">eˣ</span>
<span class="example-btn" data-fn="exp(x)">exp(x)</span>
<span class="example-btn" data-fn="2^x">2ˣ</span>
<span class="example-btn" data-fn="ln(x)">ln(x)</span>
<span class="example-btn" data-fn="log(x)">log(x)</span>
</div>
<div class="examples-row">
<span class="example-label">复合/特殊</span>
<span class="example-btn" data-fn="abs(x)">|x|</span>
<span class="example-btn" data-fn="x*sin(x)">x·sin(x)</span>
<span class="example-btn" data-fn="x^2*sin(x)">x²·sin(x)</span>
<span class="example-btn" data-fn="e^(-x^2)">e^(-x²)</span>
<span class="example-btn" data-fn="sin(x)/x">sin(x)/x</span>
</div>
<div class="hint">
支持的运算符:<code>+</code> <code>-</code> <code>*</code> <code>/</code> <code>^</code>(乘方)<code>( )</code><br>
支持的函数:<code>sin</code> <code>cos</code> <code>tan</code> <code>exp</code> <code>ln</code> <code>log</code> <code>sqrt</code> <code>abs</code> <code>pi</code> <code>e</code><br>
<strong>提示:</strong>在图像上按住鼠标左右拖动可以平移视图,使用上方的 + / − 按钮缩放视图。
</div>
<div id="errorMsg"></div>
</div>
<div class="panel">
<canvas id="canvas" width="960" height="500"></canvas>
<div class="legend">
<div class="legend-item"><div class="legend-color" style="background: #3498db;"></div><span>f(x)</span></div>
<div class="legend-item"><div class="legend-color" style="background: #e67e22;"></div><span>f'(x)</span></div>
</div>
<div class="info">
<div class="info-item"><span>鼠标位置 x:</span><strong id="mouseX">-</strong></div>
<div class="info-item"><span>f(x):</span><strong id="mouseY">-</strong></div>
<div class="info-item"><span>f'(x) ≈</span><strong id="mouseDy">-</strong></div>
</div>
</div>
<div class="panel">
<h3 style="margin-bottom: 14px; color: #2c3e50;">点定位</h3>
<div class="controls">
<div class="control-group">
<label for="pointX">已知 x 求 f(x)</label>
<input type="number" id="pointX" class="range-input" placeholder="输入 x" step="any">
</div>
<button id="calcFromX">计算</button>
<div class="control-group" style="margin-left: 20px;">
<label for="pointY">已知 f(x) 求 x</label>
<input type="number" id="pointY" class="range-input" placeholder="输入 y" step="any">
</div>
<button id="calcFromY">计算</button>
</div>
<div id="pointResult" class="point-result"></div>
</div>
</div>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const functionInput = document.getElementById('functionInput');
const plotBtn = document.getElementById('plotBtn');
const clearBtn = document.getElementById('clearBtn');
const zoomInBtn = document.getElementById('zoomInBtn');
const zoomOutBtn = document.getElementById('zoomOutBtn');
const showDerivativeCheckbox = document.getElementById('showDerivative');
const errorMsg = document.getElementById('errorMsg');
const mouseXEl = document.getElementById('mouseX');
const mouseYEl = document.getElementById('mouseY');
const mouseDyEl = document.getElementById('mouseDy');
const pointXInput = document.getElementById('pointX');
const pointYInput = document.getElementById('pointY');
const calcFromXBtn = document.getElementById('calcFromX');
const calcFromYBtn = document.getElementById('calcFromY');
const pointResultEl = document.getElementById('pointResult');
// 词法分析:把输入字符串拆成 token
function tokenize(expr) {
const tokens = [];
let i = 0;
expr = expr.replace(/\s+/g, '');
while (i < expr.length) {
const ch = expr[i];
if (/[0-9]/.test(ch) || (ch === '.' && /[0-9]/.test(expr[i+1]))) {
let num = '';
while (i < expr.length && (/[0-9]/.test(expr[i]) || expr[i] === '.')) {
num += expr[i];
i++;
}
tokens.push({ type: 'number', value: parseFloat(num) });
} else if (/[a-zA-Z]/.test(ch)) {
let name = '';
while (i < expr.length && /[a-zA-Z]/.test(expr[i])) {
name += expr[i];
i++;
}
tokens.push({ type: 'name', value: name });
} else if ('+-*/^()'.includes(ch)) {
tokens.push({ type: 'op', value: ch });
i++;
} else {
throw new Error(`无法识别的字符: ${ch}`);
}
}
return tokens;
}
// 调度场算法:中缀表达式转后缀表达式(RPN)
function toRPN(tokens) {
const output = [];
const ops = [];
const precedence = { '+': 1, '-': 1, '*': 2, '/': 2, '^': 3 };
const rightAssoc = { '^': true };
const funcs = ['sin', 'cos', 'tan', 'exp', 'ln', 'log', 'sqrt', 'abs'];
const isFunction = (tok) => tok && tok.type === 'name' && funcs.includes(tok.value);
let prev = null;
for (let i = 0; i < tokens.length; i++) {
const tok = tokens[i];
if (tok.type === 'number') {
output.push(tok);
} else if (tok.type === 'name') {
if (tok.value === 'x' || tok.value === 'pi' || tok.value === 'e') {
output.push(tok);
} else if (isFunction(tok)) {
ops.push(tok);
} else {
throw new Error(`未知符号: ${tok.value}`);
}
} else if (tok.value === '(') {
ops.push(tok);
} else if (tok.value === ')') {
while (ops.length && ops[ops.length - 1].value !== '(') {
output.push(ops.pop());
}
if (!ops.length) throw new Error('括号不匹配');
ops.pop(); // 弹出 '('
if (ops.length && isFunction(ops[ops.length - 1])) {
output.push(ops.pop());
}
} else if (tok.type === 'op') {
// 处理一元负号
if (tok.value === '-' && (prev === null || prev.value === '(' || prev.type === 'op')) {
output.push({ type: 'number', value: 0 });
}
while (ops.length && ops[ops.length-1].value !== '(' && !isFunction(ops[ops.length-1]) &&
(precedence[ops[ops.length-1].value] > precedence[tok.value] ||
(precedence[ops[ops.length-1].value] === precedence[tok.value] && !rightAssoc[tok.value]))) {
output.push(ops.pop());
}
ops.push(tok);
}
prev = tok;
}
while (ops.length) {
const op = ops.pop();
if (op.value === '(' || op.value === ')') throw new Error('括号不匹配');
output.push(op);
}
return output;
}
// 计算后缀表达式在给定 x 下的值
function evalRPN(rpn, x) {
const stack = [];
const funcs = {
sin: Math.sin, cos: Math.cos, tan: Math.tan,
exp: Math.exp, ln: Math.log, log: Math.log10,
sqrt: Math.sqrt, abs: Math.abs
};
const consts = { pi: Math.PI, e: Math.E };
for (const tok of rpn) {
if (tok.type === 'number') {
stack.push(tok.value);
} else if (tok.type === 'name') {
if (tok.value === 'x') {
stack.push(x);
} else if (consts.hasOwnProperty(tok.value)) {
stack.push(consts[tok.value]);
} else if (funcs.hasOwnProperty(tok.value)) {
if (!stack.length) throw new Error(`函数 ${tok.value} 缺少参数`);
const arg = stack.pop();
stack.push(funcs[tok.value](arg));
} else {
throw new Error(`未知符号: ${tok.value}`);
}
} else if (tok.type === 'op') {
if (stack.length < 2) throw new Error('表达式格式错误');
const b = stack.pop();
const a = stack.pop();
switch (tok.value) {
case '+': stack.push(a + b); break;
case '-': stack.push(a - b); break;
case '*': stack.push(a * b); break;
case '/': stack.push(a / b); break;
case '^': stack.push(Math.pow(a, b)); break;
}
}
}
if (stack.length !== 1) throw new Error('表达式格式错误');
return stack[0];
}
function createFunction(expr) {
const tokens = tokenize(expr);
const rpn = toRPN(tokens);
return function(x) {
return evalRPN(rpn, x);
};
}
// 安全求值
function safeEval(f, x) {
try {
const y = f(x);
return isFinite(y) ? y : NaN;
} catch (e) {
return NaN;
}
}
// 数值求导(优先中心差分,边界处退化为单边差分)
function derivative(f, x) {
const h = 1e-6;
let y1 = safeEval(f, x + h);
let y2 = safeEval(f, x - h);
if (isFinite(y1) && isFinite(y2)) {
return (y1 - y2) / (2 * h);
}
// 尝试前向差分
y1 = safeEval(f, x + h);
y2 = safeEval(f, x);
if (isFinite(y1) && isFinite(y2)) {
return (y1 - y2) / h;
}
// 尝试后向差分
y1 = safeEval(f, x);
y2 = safeEval(f, x - h);
if (isFinite(y1) && isFinite(y2)) {
return (y1 - y2) / h;
}
return NaN;
}
const DEFAULT_X_MIN = -5;
const DEFAULT_X_MAX = 5;
let currentFn = null;
let currentXMin = DEFAULT_X_MIN;
let currentXMax = DEFAULT_X_MAX;
function resetView() {
currentXMin = DEFAULT_X_MIN;
currentXMax = DEFAULT_X_MAX;
}
function zoomView(factor) {
const center = (currentXMin + currentXMax) / 2;
let newRange = (currentXMax - currentXMin) * factor;
const MIN_RANGE = 1e-10;
const MAX_RANGE = 1e10;
if (newRange < MIN_RANGE) newRange = MIN_RANGE;
if (newRange > MAX_RANGE) newRange = MAX_RANGE;
currentXMin = center - newRange / 2;
currentXMax = center + newRange / 2;
draw();
}
function draw() {
errorMsg.textContent = '';
const expr = functionInput.value;
if (currentXMin >= currentXMax) {
currentXMin = DEFAULT_X_MIN;
currentXMax = DEFAULT_X_MAX;
}
try {
currentFn = createFunction(expr);
} catch (e) {
errorMsg.textContent = '表达式错误:' + e.message;
currentFn = null;
return;
}
const width = canvas.width;
const height = canvas.height;
const padding = 40;
const plotWidth = width - 2 * padding;
const plotHeight = height - 2 * padding;
// 清空画布
ctx.clearRect(0, 0, width, height);
// 计算 y 范围
const xStep = (currentXMax - currentXMin) / plotWidth;
const showDerivative = showDerivativeCheckbox.checked;
let yMin = Infinity, yMax = -Infinity;
for (let px = 0; px <= plotWidth; px++) {
const x = currentXMin + px * xStep;
const y = safeEval(currentFn, x);
if (isFinite(y)) {
if (y < yMin) yMin = y;
if (y > yMax) yMax = y;
}
if (showDerivative) {
const dy = derivative(currentFn, x);
if (isFinite(dy)) {
if (dy < yMin) yMin = dy;
if (dy > yMax) yMax = dy;
}
}
}
if (!isFinite(yMin) || !isFinite(yMax) || yMin === yMax) {
yMin = -5;
yMax = 5;
}
const yPadding = (yMax - yMin) * 0.1 || 1;
yMin -= yPadding;
yMax += yPadding;
currentYMin = yMin;
currentYMax = yMax;
// 坐标转换
function toCanvasX(x) {
return padding + (x - currentXMin) / (currentXMax - currentXMin) * plotWidth;
}
function toCanvasY(y) {
return height - padding - (y - yMin) / (yMax - yMin) * plotHeight;
}
// 绘制网格
ctx.strokeStyle = '#e0e4e8';
ctx.lineWidth = 1;
const xGridCount = 10;
const yGridCount = 8;
ctx.beginPath();
for (let i = 0; i <= xGridCount; i++) {
const x = currentXMin + (currentXMax - currentXMin) * i / xGridCount;
const cx = toCanvasX(x);
ctx.moveTo(cx, padding);
ctx.lineTo(cx, height - padding);
}
for (let i = 0; i <= yGridCount; i++) {
const y = yMin + (yMax - yMin) * i / yGridCount;
const cy = toCanvasY(y);
ctx.moveTo(padding, cy);
ctx.lineTo(width - padding, cy);
}
ctx.stroke();
// 绘制坐标轴
ctx.strokeStyle = '#7f8c8d';
ctx.lineWidth = 2;
ctx.beginPath();
const originX = toCanvasX(0);
const originY = toCanvasY(0);
if (originY >= padding && originY <= height - padding) {
ctx.moveTo(padding, originY);
ctx.lineTo(width - padding, originY);
}
if (originX >= padding && originX <= width - padding) {
ctx.moveTo(originX, padding);
ctx.lineTo(originX, height - padding);
}
ctx.stroke();
// 绘制刻度标签
ctx.fillStyle = '#666';
ctx.font = '12px sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'top';
for (let i = 0; i <= xGridCount; i++) {
const x = currentXMin + (currentXMax - currentXMin) * i / xGridCount;
const cx = toCanvasX(x);
if (cx >= padding && cx <= width - padding) {
ctx.fillText(parseFloat(x.toFixed(2)), cx, height - padding + 6);
}
}
ctx.textAlign = 'right';
ctx.textBaseline = 'middle';
for (let i = 0; i <= yGridCount; i++) {
const y = yMin + (yMax - yMin) * i / yGridCount;
const cy = toCanvasY(y);
if (cy >= padding && cy <= height - padding) {
ctx.fillText(parseFloat(y.toFixed(2)), padding - 8, cy);
}
}
// 通用曲线绘制辅助函数
function plotCurve(evaluator, color, lineWidth) {
ctx.strokeStyle = color;
ctx.lineWidth = lineWidth;
ctx.beginPath();
let first = true;
for (let px = 0; px <= plotWidth; px++) {
const x = currentXMin + px * xStep;
const y = evaluator(x);
if (!isFinite(y)) {
first = true;
continue;
}
const cx = toCanvasX(x);
const cy = toCanvasY(y);
if (first) {
ctx.moveTo(cx, cy);
first = false;
} else {
ctx.lineTo(cx, cy);
}
}
ctx.stroke();
}
// 绘制原函数 f(x)
plotCurve(x => safeEval(currentFn, x), '#3498db', 2.5);
// 绘制导函数 f'(x)
if (showDerivative) {
plotCurve(x => derivative(currentFn, x), '#e67e22', 2.5);
}
// 绘制定位点标记
function drawPointMarkers() {
if (!activePoints.length) return;
for (const pt of activePoints) {
const y = safeEval(currentFn, pt.x);
if (!isFinite(y)) continue;
const cx = toCanvasX(pt.x);
const cy = toCanvasY(y);
if (cx < padding || cx > width - padding || cy < padding || cy > height - padding) continue;
ctx.strokeStyle = pt.type === 'fromX' ? '#27ae60' : '#9b59b6';
ctx.fillStyle = pt.type === 'fromX' ? '#27ae60' : '#9b59b6';
ctx.lineWidth = 1.5;
// 十字准星
ctx.setLineDash([4, 4]);
ctx.beginPath();
ctx.moveTo(cx, padding);
ctx.lineTo(cx, height - padding);
ctx.moveTo(padding, cy);
ctx.lineTo(width - padding, cy);
ctx.stroke();
ctx.setLineDash([]);
// 中心点
ctx.beginPath();
ctx.arc(cx, cy, 5, 0, Math.PI * 2);
ctx.fill();
}
}
// 绘制函数公式标签
ctx.font = 'bold 13px sans-serif';
ctx.textAlign = 'left';
ctx.textBaseline = 'top';
const labelX = padding + 12;
const labelY = padding + 10;
ctx.fillStyle = '#3498db';
ctx.fillText('f(x) = ' + (expr || '未输入'), labelX, labelY);
if (showDerivative) {
ctx.fillStyle = '#e67e22';
ctx.fillText("f'(x) ≈ [f(x+h) - f(x-h)] / (2h)", labelX, labelY + 20);
}
// 标注由点定位计算出的位置
drawPointMarkers();
}
let currentYMin = -5;
let currentYMax = 5;
let activePoints = [];
// 二分法求根:在 [a,b] 上找 f(x) = target 的解(假设两端异号)
function bisect(f, a, b, target, tol) {
let fa = safeEval(f, a) - target;
let fb = safeEval(f, b) - target;
if (!isFinite(fa) || !isFinite(fb)) return NaN;
if (fa === 0) return a;
if (fb === 0) return b;
if (fa * fb > 0) return NaN;
for (let i = 0; i < 60; i++) {
const mid = (a + b) / 2;
const fm = safeEval(f, mid) - target;
if (!isFinite(fm)) return NaN;
if (Math.abs(fm) < tol || (b - a) < tol) return mid;
if (fa * fm <= 0) {
b = mid;
fb = fm;
} else {
a = mid;
fa = fm;
}
}
return (a + b) / 2;
}
// 扫描视图范围,寻找 f(x) = targetY 的所有解
function findRootsForY(targetY) {
if (!currentFn) return [];
const roots = [];
const samples = 400;
const step = (currentXMax - currentXMin) / samples;
let prevX = currentXMin;
let prevVal = safeEval(currentFn, prevX) - targetY;
for (let i = 1; i <= samples; i++) {
const x = currentXMin + i * step;
const val = safeEval(currentFn, x) - targetY;
if (!isFinite(val) || !isFinite(prevVal)) {
prevX = x;
prevVal = val;
continue;
}
if (val === 0) {
roots.push(x);
} else if (prevVal !== 0 && prevVal * val < 0) {
const root = bisect(currentFn, prevX, x, targetY, 1e-10);
if (isFinite(root)) roots.push(root);
}
prevX = x;
prevVal = val;
}
// 去重(容差内)
const unique = [];
for (const r of roots) {
if (!unique.some(u => Math.abs(u - r) < 1e-6)) {
unique.push(r);
}
}
return unique;
}
function formatNum(n) {
if (!isFinite(n)) return '无定义';
return parseFloat(n.toFixed(6)).toString();
}
canvas.addEventListener('mousemove', function(e) {
if (!currentFn) return;
const rect = canvas.getBoundingClientRect();
const px = e.clientX - rect.left;
const py = e.clientY - rect.top;
const padding = 40;
const plotWidth = canvas.width - 2 * padding;
const plotHeight = canvas.height - 2 * padding;
if (isDragging) {
const dx = px - dragStartX;
const xRange = dragStartXMax - dragStartXMin;
const shift = -dx * xRange / plotWidth;
currentXMin = dragStartXMin + shift;
currentXMax = dragStartXMax + shift;
draw();
return;
}
if (px < padding || px > canvas.width - padding || py < padding || py > canvas.height - padding) {
mouseXEl.textContent = '-';
mouseYEl.textContent = '-';
mouseDyEl.textContent = '-';
return;
}
const x = currentXMin + (px - padding) / plotWidth * (currentXMax - currentXMin);
let y;
try {
y = currentFn(x);
} catch (e) {
mouseYEl.textContent = '错误';
return;
}
if (!isFinite(y)) {
mouseXEl.textContent = x.toFixed(4);
mouseYEl.textContent = '无定义';
mouseDyEl.textContent = '-';
} else {
mouseXEl.textContent = x.toFixed(4);
mouseYEl.textContent = y.toFixed(4);
const dy = derivative(currentFn, x);
mouseDyEl.textContent = isFinite(dy) ? dy.toFixed(4) : '无定义';
}
// 重绘并显示指示线
draw();
const cx = padding + (x - currentXMin) / (currentXMax - currentXMin) * plotWidth;
const cy = canvas.height - padding - (y - currentYMin) / (currentYMax - currentYMin) * plotHeight;
if (isFinite(y)) {
ctx.strokeStyle = '#e74c3c';
ctx.lineWidth = 1;
ctx.setLineDash([5, 5]);
ctx.beginPath();
ctx.moveTo(cx, padding);
ctx.lineTo(cx, canvas.height - padding);
ctx.moveTo(padding, cy);
ctx.lineTo(canvas.width - padding, cy);
ctx.stroke();
ctx.setLineDash([]);
ctx.fillStyle = '#e74c3c';
ctx.beginPath();
ctx.arc(cx, cy, 5, 0, Math.PI * 2);
ctx.fill();
}
});
let isDragging = false;
let dragStartX = 0;
let dragStartXMin = 0;
let dragStartXMax = 0;
canvas.addEventListener('mousedown', function(e) {
if (e.button !== 0) return;
const rect = canvas.getBoundingClientRect();
const px = e.clientX - rect.left;
const py = e.clientY - rect.top;
const padding = 40;
if (px < padding || px > canvas.width - padding || py < padding || py > canvas.height - padding) return;
isDragging = true;
dragStartX = px;
dragStartXMin = currentXMin;
dragStartXMax = currentXMax;
canvas.style.cursor = 'grabbing';
});
canvas.addEventListener('mouseup', function() {
isDragging = false;
canvas.style.cursor = 'grab';
});
canvas.addEventListener('mouseleave', function() {
isDragging = false;
canvas.style.cursor = 'grab';
mouseXEl.textContent = '-';
mouseYEl.textContent = '-';
mouseDyEl.textContent = '-';
draw();
});
// 示例按钮:在光标位置插入函数
document.querySelectorAll('.example-btn').forEach(btn => {
btn.addEventListener('click', function() {
const text = this.dataset.fn;
const start = functionInput.selectionStart || 0;
const end = functionInput.selectionEnd || 0;
const current = functionInput.value;
functionInput.value = current.slice(0, start) + text + current.slice(end);
functionInput.focus();
const newPos = start + text.length;
functionInput.setSelectionRange(newPos, newPos);
draw();
});
});
plotBtn.addEventListener('click', draw);
showDerivativeCheckbox.addEventListener('change', draw);
functionInput.addEventListener('keydown', function(e) {
if (e.key === 'Enter') draw();
});
clearBtn.addEventListener('click', function() {
functionInput.value = '';
resetView();
activePoints = [];
pointResultEl.textContent = '';
draw();
});
zoomInBtn.addEventListener('click', function() {
zoomView(0.75);
});
zoomOutBtn.addEventListener('click', function() {
zoomView(1.3333333333333333);
});
calcFromXBtn.addEventListener('click', function() {
if (!currentFn) {
pointResultEl.textContent = '请先输入并绘制函数。';
return;
}
const x = parseFloat(pointXInput.value);
if (!isFinite(x)) {
pointResultEl.textContent = '请输入有效的 x 值。';
return;
}
const y = safeEval(currentFn, x);
const dy = derivative(currentFn, x);
if (!isFinite(y)) {
pointResultEl.textContent = `在 x = ${formatNum(x)} 处函数无定义。`;
activePoints = [];
} else {
pointResultEl.innerHTML = `x = <strong>${formatNum(x)}</strong> 时,f(x) = <strong>${formatNum(y)}</strong>,f'(x) ≈ <strong>${formatNum(dy)}</strong>`;
activePoints = [{ x, type: 'fromX' }];
}
draw();
});
calcFromYBtn.addEventListener('click', function() {
if (!currentFn) {
pointResultEl.textContent = '请先输入并绘制函数。';
return;
}
const y = parseFloat(pointYInput.value);
if (!isFinite(y)) {
pointResultEl.textContent = '请输入有效的 y 值。';
return;
}
const roots = findRootsForY(y);
if (roots.length === 0) {
pointResultEl.textContent = `在视图范围内未找到 f(x) = ${formatNum(y)} 的解。`;
activePoints = [];
} else {
const items = roots.map(r => {
const fy = safeEval(currentFn, r);