-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCanvas_demo.html
71 lines (70 loc) · 2.98 KB
/
Canvas_demo.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Canvas</title>
</head>
<body>
<canvas id="demo" width="500" height="400">
<p>你的浏览器不支持Canvas</p>
</canvas>
<img src="" id="canvass"/>
</body>
<script>
let canvas = document.getElementById('demo'); // 获取 canvas 对象
let ctx = canvas.getContext('2d'); // 获取绘图上下文(画笔)
ctx.rect(0,0,500,400); // 填充一个矩形
ctx.fillStyle='#FFFFFF'; // 设置填充背景色
ctx.fill(); // 填充
ctx.beginPath(); // 开始绘制一个路径
ctx.fillStyle = 'rgba(125,125,125,0.3)'; // 设置填充色
ctx.rect(100,150,50,50); // 填充一个矩形
let grd = ctx.createLinearGradient(100,150,150,175); // 创建线性渐变
grd.addColorStop(0,'#333333'); // 创建起点
grd.addColorStop(1,'rgba(125,125,125,0.3)'); // 创建终点
ctx.fillStyle = grd; // 设置填充色为刚刚创建的渐变
ctx.fill(); // 填充
ctx.closePath(); // 闭合路径
ctx.fillStyle='rgba(125,125,125,0.5)'; // 设置填充色
ctx.beginPath(); // 开始绘制一个路径
ctx.moveTo(170,180); // 将画笔移动到坐标位置
ctx.lineTo(210,230); // 画笔从当前位置绘制一条线到指定位置
ctx.lineTo(230,260);
ctx.fill(); // 填充
ctx.closePath(); // 闭合路径
ctx.beginPath(); // 开始绘制路径
ctx.lineWidth=0.5; // 设置线条宽度
ctx.arc(270,200,30,0,2*Math.PI,false); // 绘制一个圆弧
ctx.stroke(); // 填充边框
ctx.closePath(); // 闭合路径
ctx.fillStyle='#999999'; // 设置填充色
ctx.font='14px FiraCode'; // 设置字体样式
ctx.fillText('Canvas',100,250,100); // 填充文字
ctx.save(); // 保存当前 canvas 状态
let image_url = canvas.toDataURL('image/png'); // 将canvas 转为 base64 编码
document.getElementById('canvass').src = image_url; // 将base64 数据赋给一个img 标签的src 属性
// 开始将base64 数据转为 mime 格式
let arr = image_url.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
let res = new File([u8arr],'demo.png',{type:mime}); // 解码后的数据保存为一个文件
document.onkeyup=function (e){ // 按下回车键时,触发保存文件
if (e.key === 'Enter'){
save_file(res,'demo.png');
}
};
function save_file(data,filename) // 文件下载到本地
{
let a = document.createElement('a');
let event = new MouseEvent('click');
a.download = filename; // 保存的文件名
a.href = image_url; // 下载的地址base64
a.dispatchEvent(event); // 派发自定义的下载事件
}
window.console.log = function (e) {
};
console.log('hello');
</script>
</html>