-
Notifications
You must be signed in to change notification settings - Fork 1
/
canvas.html
88 lines (88 loc) · 3.54 KB
/
canvas.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>简易图形画图工具(Canvas绘制测试)</title>
<link rel="stylesheet" type="text/css" href="style.css">
<style>
.btn {
display: inline-block;
width: 100px;
height: 20px;
background-color: green;
text-align: center;
}
input[type=number] {
width: 3em;
}
div.center {
max-width: 500px;
}
</style>
</head>
<body>
<div class="center">
<h1 class="title">简易图形画图工具</h1>
<canvas id="canvas" width="400" height="300"></canvas><br />
颜色 <input type="color" id="color">
宽 <input type="number" id="width">
高 <input type="number" id="height">
X坐标 <input type="number" id="pos-x">
Y坐标 <input type="number" id="pos-y"><br />
<div onclick="circle()" class="btn">绘制圆形</div>
<div onclick="rect()" class="btn">绘制方形</div>
<div onclick="triangle()" class="btn">绘制三角形</div>
<div onclick="text()" class="btn">添加文本</div>
</div>
</body>
<script>
var ctx = document.getElementById("canvas").getContext("2d");
function rect() {
var x = Number(document.getElementById("pos-x").value);
var y = Number(document.getElementById("pos-y").value);
var w = Number(document.getElementById("width").value);
var h = Number(document.getElementById("height").value);
var color = document.getElementById("color").value;
ctx.fillStyle = color;
ctx.fillRect(x - (w / 2),y - (h / 2),w,h);
}
function triangle() {
var x = Number(document.getElementById("pos-x").value);
var y = Number(document.getElementById("pos-y").value);
var w = Number(document.getElementById("width").value);
var h = Number(document.getElementById("height").value);
var color = document.getElementById("color").value;
ctx.fillStyle = color;
ctx.beginPath();
ctx.moveTo(x,y);
ctx.moveTo(x,y + (h / 2));
ctx.lineTo(x - (w / 2),y + (h / 2));
ctx.lineTo(x,y - (h / 2));
ctx.lineTo(x + (w / 2),y + (h / 2));
ctx.lineTo(x,y + (h / 2));
ctx.closePath();
ctx.fill();
}
function circle() {
var x = Number(document.getElementById("pos-x").value);
var y = Number(document.getElementById("pos-y").value);
var w = Number(document.getElementById("width").value);
var color = document.getElementById("color").value;
ctx.fillStyle = color;
ctx.arc(x,y,w / 2,0,Math.PI * 2);
ctx.fill();
}
function text() {
var x = Number(document.getElementById("pos-x").value);
var y = Number(document.getElementById("pos-y").value);
var width = document.getElementById("width").value;
var color = document.getElementById("color").value;
ctx.fillStyle = color;
var text = prompt("请输入文本:");
var font = prompt("请输入字体:","serif");
ctx.font = width + "px " + font;
ctx.textAlign = "center";
ctx.fillText(text,x,y);
}
</script>
</html>