canvas添加事件

1
<canvas id="c1" width="800" height="600"></canvas>

画布内的元素移动

1
2
3
4
5
6
7
8
9
10
11
12
window.onload = function () {
//图形动起来

let oC = document.getElementById("c1");
let gd = oC.getContext("2d");
let L = 50;
setInterval(() => {
gd.clearRect(0, 0, oC.width, oC.height); //清除整个画布
L++;
gd.strokeRect(L, 50, 100, 70);
}, 10);
};

画布内的矩形元素添加事件

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
window.onload = function () {
//点击事件
let oC = document.getElementById("c1");
let gd = oC.getContext("2d");
let l = 50,
t = 50,
w = 100,
h = 70;
gd.strokeRect(l, t, w, h);
oC.onclick = function (e) {
gd.clearRect(0, 0, oC.width, oC.height);
if (
e.offsetX >= l &&
e.offsetX <= l + w &&
e.offsetY >= t &&
e.offsetY <= t + h
) {
gd.strokeStyle = "red";
gd.strokeRect(l, t, w, h);
} else {
gd.strokeStyle = "blue";
gd.strokeRect(l, t, w, h);
}
};
};

画布圆心区域添加事件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
window.onload = function () {
let oC = document.getElementById("c1");
let gd = oC.getContext("2d");
let cx = 400,
cy = 300,
r = 200;
gd.arc(cx, cy, r, 0, 2 * Math.PI, true);
gd.fillStyle = "yellow";
gd.fill();
oC.onmousemove = function (e) {
let a = e.offsetX - cx;
let b = e.offsetY - cy;
let dis = Math.sqrt(a * a + b * b);
gd.beginPath();
gd.arc(cx, cy, r, 0, 2 * Math.PI, true);
if (dis <= r) {
gd.fillStyle = "blue";
} else {
gd.fillStyle = "red";
}
gd.fill();
};
};