實現這個思路的方法就是使用canvas對象的context的2d對象的方法:isPointInPath
我們可以通過這個方法判斷繪製的圖形,以及自己通過隨機的點繪製的2d圖形
以下是demo的源碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>isPointInPath</title>
</head>
<body>
<canvas id="ctx"></canvas>
<script>
const context = document.getElementById("ctx");
const ctx = context.getContext("2d");
const balls = [];
const lines = [];
const defaultColor = '#000';
const focusColor = '#0f0';
window.onload = function () {
context.width = 1000;
context.height = 600;
context.style.border = "1px solid red";
//添加矩形
for (let i = 0; i < 5; i++) {
const rect = {x: Math.random() * context.width, y: Math.random() * context.height, w: Math.random() * 50 + 20, h: Math.random() * 50 + 20};
balls.push(rect);
}
//添加點生成的閉合圖形
for (let i = 0; i < 5; i++) {
lines.push(randomPoi());
}
context.addEventListener("mousemove", draw);
};
function draw(e) {
const x = e.clientX - context.getBoundingClientRect().left;
const y = e.clientY - context.getBoundingClientRect().top;
for (let i = 0; i < balls.length; i++) {
ctx.beginPath();
ctx.rect(balls[i].x, balls[i].y, balls[i].w, balls[i].h);
if (ctx.isPointInPath(x, y)) {
ctx.fillStyle = focusColor;
ctx.fill();
}
else {
ctx.fillStyle = defaultColor;
ctx.fill();
}
}
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
ctx.beginPath();
ctx.moveTo(line[0].x, line[0].y);
for (let j = 1; j < line.length; j++) {
ctx.lineTo(line[j].x, line[j].y);
}
ctx.closePath();
if (ctx.isPointInPath(x, y)) {
ctx.fillStyle = focusColor;
ctx.fill();
}
else {
ctx.fillStyle = defaultColor;
ctx.fill();
}
}
}
//隨機生成n個點
function randomPoi() {
//一堆點組成的數組
const pointArr = [];
//首先生成一箇中心點
const center = {x: Math.random() * context.width, y: Math.random() * context.height};
pointArr.push(center);
//生成一個隨機點數,最少兩個點,最多六個點
const len = 2 + Math.floor(Math.random() * 5);
//根據長度生成距離中心點最大長度內的隨機點
for (let i = 0; i < len; i++) {
pointArr.push({
x: center.x + 100 * Math.random() - 50,
y: center.y + 80 * Math.random() - 40
})
}
return pointArr;
}
</script>
</body>
</html>