基于2层canvas实现rts游戏的战争迷雾效果
1,实现rts游戏中的如下迷雾:
思路:
1, 可以看到 地图的高亮从玩家控制的物体开始辐射,在一定范围内是透明色,然后超过该范围为半透明色,最后为不透明色
根据此规则,最内层可以看做纯圆形,外层可看做一个半透明的圆环
2,canvas 的新api globalCompositeOperation 定义了 每次绘图操作的叠加方式 在本例中 为 '
<html>
<head>
<meta charset="utf-8" />
<meta content="telephone=no" name="format-detection" />
<meta
content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"
name="viewport"
/>
<meta content="no-cache" http-equiv="pragma" />
<meta
content="no-cache, no-store, must-revalidate"
http-equiv="cache-control"
/>
<meta content="0" http-equiv="expires" />
<link href="data:;base64,=" rel="icon" />
</head>
<style>
* {
margin: 0;
padding: 0;
}
.text {
width: 200px;
height: 200px;
}
img {
width: 1000px;
height: 1000px;
position: absolute;
top: 0;
left: 0;
z-index: -2;
}
canvas {
width: 1000px;
height: 1000px;
position: absolute;
top: 0;
left: 0;
z-index: 2;
}
#canvas{
}
#canvas2 {
width: 1000px;
height: 1000px;
position: absolute;
top: 0;
left: 0;
z-index: 1;
}
</style>
<body>
<canvas width="1000" height="1000" id="canvas"></canvas>
<canvas width="1000" height="1000" id="canvas2"></canvas>
<img src="./bg.png" />
</body>
<body>
<script src="./lib/jquery.js"></script>
<script src="./lib/dayjs.js"></script>
<script>
var canvas = document.getElementById("canvas");
var canvas2 = document.getElementById("canvas2");
var context = canvas.getContext("2d");
context.fillStyle = "black";
context.fillRect(0, 0, 1000, 1000);
var context2 = canvas2.getContext("2d");
context2.fillStyle = "rgba(0,0,0,0.2)";
context2.fillRect(0, 0, 1000, 1000);
context2.fill();
function paint(center) {
let radialGradient1 = context.createRadialGradient(
center.x,
center.y,
180,
center.x,
center.y,
300
);
radialGradient1.addColorStop(0, "rgba(0,0,0,0.9)");
radialGradient1.addColorStop(1, "rgba(0,0,0,0.01)");
context2.beginPath()
context.globalCompositeOperation = "destination-out";
context.fillStyle = radialGradient1;
context.arc(center.x, center.y, 300, 0, Math.PI * 2, true);
context.fill();
}
function paint2(center) {
let radialGradient1 = context2.createRadialGradient(
center.x,
center.y,
120,
center.x,
center.y,
200
);
radialGradient1.addColorStop(0, "rgba(0,0,0,0.9)");
radialGradient1.addColorStop(1, "rgba(0,0,0,0.01)");
context2.globalCompositeOperation = "destination-out";
context2.beginPath()
context2.fillStyle = radialGradient1;
context2.arc(center.x, center.y, 200, 0, Math.PI * 2, true);
context2.fill();
}
let timer = null;
canvas.onmousemove = (e) => {
if (!timer) {
timer = setTimeout(() => {
let center = {
x: e.clientX,
y: e.clientY,
};
paint(center);
paint2(center)
timer = null;
}, 10);
}
// paint2(center);
};
</script>
</body>
</html>
效果如下: