利用js生成一百以内的加减运算题

孩子五岁了,最近对算数题很感兴趣,于是写了一个小程序,自动生成一百以内的加减法运算题,可以打印出来,让孩子练习。

核心程序非常简单,就是利用js的随机数生成器,自动随机生成加减法运算题目和答案,答案和题目可以分开输出。

需求描述

  1. 生成一百以内的加减法运算题目
  2. 生成的题目和答案可以分开输出
  3. 可以指定生成的题目数量
  4. 可以指定生成的题目的最大值,默认为100
  5. 可以指定生成的题目的最小值,默认为0
  6. 可以指定生成的题目的运算符,默认为加减法
  7. 排除ab/ba这种重复的题目

核心源码

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
function generateMathProblems(
num,
max = 100,
min = 0,
operator = ["+", "-"]
) {
const problems = [];
const answers = [];
const set = new Set();
while (set.size < num) {
// 生成随机数
let num1 = Math.floor(Math.random() * (max - min) + min);
let num2 = Math.floor(Math.random() * (max - min) + min);
if (num1 === 0 || num2 === 0) {
continue;
}
let operatorStr =
operator[Math.floor(Math.random() * operator.length)];
let answer = "";
if (operatorStr === "-") {
if (num1 < num2) {
[num1, num2] = [num2, num1];
}
}
const key = [num1, num2].sort((a, b) => b - a).join(operatorStr);
if (set.has(key)) {
continue;
}
// 计算答案
switch (operatorStr) {
case "+":
answer = num1 + num2;
break;
case "-":
answer = num1 - num2;
break;
case "++":
answer = num1 + num2 + min;
break;
case "--":
answer = num1 - num2 - min;
break;
default:
break;
}
// 生成题目和答案
const problem = `${num1} ${operatorStr} ${num2} = ___`;
problems.push(problem);
answers.push(answer);
set.add(key);
}
console.log(set);
return {
problems: problems,
answers: answers,
};
}

generateMathProblems()函数接受4个参数,分别是题目数量、最大值、最小值、运算符。
函数内通过循环生成指定数量的题目和答案,利用数组进行存储并返回。
首先在指定范围内生成两个随机数,用来构造算式。
在指定的运算符范围内,生成运算符字符串。
根据运算符字符串计算出答案。
最后将算式和答案存储在数组中,并返回存储题目和答案的对象。

打印

实现排版打印,可以利用html2canvas和jspdf两个库,将html转换成canvas,然后再将canvas转换成pdf。

引入 html2canvas 和 jsPDF 库

在 HTML 文件中引入 html2canvas 和 jsPDF 库:

1
2
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.0.0/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js"></script>

编写转换函数

使用 html2canvas 将 HTML 元素转换成 Canvas,再使用 jsPDF 将 Canvas 转换成 PDF。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function htmlToPdf(htmlElement, fileName) {
// 设置页面大小和间距
const pdfWidth = htmlElement.offsetWidth;
const pdfHeight = htmlElement.offsetHeight;
const topMargin = 10;
const bottomMargin = 10;

// 将 HTML 元素转换成 Canvas
html2canvas(htmlElement, {
background: '#fff',
scale: 2 // 倍数,提高清晰度
}).then(canvas => {
const image = canvas.toDataURL('image/png');
const pdf = new jsPDF('p', 'pt', [pdfWidth, pdfHeight]);
// 将 Canvas 转换成 PDF
pdf.addImage(image, 'PNG', 0, topMargin, pdfWidth, pdfHeight);
pdf.save(fileName + '.pdf');
});
}

调用转换函数

将需要转换的 HTML 元素传入转换函数,并指定保存的文件名:

1
2
3
const element = document.querySelector('#pdf-content');
const fileName = 'my-document';
htmlToPdf(element, fileName);

其中,element 是需要转换成 PDF 的 HTML 元素,fileName 是保存的文件名。在这个例子中,我将 HTML 元素的 id 设置为 pdf-content

demo地址:https://www.mulianju.com/demos/gen-sums/

本文永久链接: https://www.mulianju.com/gen-sums/