code1024
今天在开源中国上发现一个有意思的项目:code1024,利用纯数学计算和canvas画出一些漂亮的图形。像这样:

看到这里我就想自己实现一个,看一下我的代码(uni-app)。
// html
//<canvas canvas-id="canvas-p" id="canvas" style="width: 512px; height: 512px;"></canvas>
// js
mounted(){
this.canvasP = document.getElementById("canvas");
const ctx = uni.createCanvasContext('canvas-p', this);
for(let i = 0; i < this.canvasP.width; i++){
for(let j = 0; j < this.canvasP.height; j++){
ctx.setFillStyle(this.getColorByFunc(i, j));
ctx.fillRect(i, j, 1, 1);
}
}
ctx.draw();
uni.canvasToTempFilePath({
x: 0,
y: 0,
width: this.canvasP.width,
height: this.canvasP.height,
canvasId: id,
success: (rest) => {
var savedFilePath = rest.tempFilePath;//相对路径 base64
this.src = savedFilePath;
}
});
}
methods: {
// 传入坐标返回颜色值
getColorByFunc(x, y){
//var a=0,b=0,d,n=0,r=0,g=0;
//for(;a*a+(d=b*b)<4&&n++<4096;b=2*a*b+y/2.5e4+.06,a=a*a-d+x/2.5e4+.34);
//r=n/4;
//g=2*r;
//b=4*r;
return `rgb(${r},${g},${b})`;
//return [r,g,b,255];
},
}
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
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
ok!一口气写完运行,....WTF?卡顿将近10秒,结果发现是setFillStyle和fillRect使用太频繁引起的。
技术有限看源码吧,研究作者的代码发现作者使用了getImageData和putImageData,前者是获取canvas区域的像素数据、后者是把颜色数据绘制到canvas上,有了这两个就可以直接操作像素数据极大的减少对canva本身的操作。修改代码如下:
this.canvasP = document.getElementById("canvas");
let width = 512, height = 512;
// uni-app没有getImageData 但是实现了canvasGetImageData API用法一样
uni.canvasGetImageData({
canvasId: 'canvas-p',
x: 0,
y: 0,
width: width,
height: height,
success: (res) => {
let imageData = res.data;
let index = 0;
for(let i = 0; i < width; i++){
for(let j = 0; j < height; j++){
let rgb = this.getColorByFunc(i, j);// ctx.setFillStyle(this.getColorByFunc(i, j));
imageData[index++] = rgb[0];
imageData[index++] = rgb[1];
imageData[index++] = rgb[2];
imageData[index++] = rgb[3];
}
}
// uni-app没有putImageData
uni.canvasPutImageData({
canvasId: 'canvas-p',
data: imageData,
x: 0,
y: 0,
width: width,
height: height
})
}
});
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
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
运行,完美!没有丝毫卡顿。 总结一下:在uni-app上没法使用dom设置canvas的宽高,所有这里采用style设置同比缩减了一般宽高,在计算颜色代码上与作者有点差别。我还有一个问题,如果把颜色值绘制到canvas上也就是位图(bitmap),那bitmap是怎样转换png或jpg?
上次更新: 2025/09/05, 8:09:00