本人经过多种ai生成,后研究createRadialGradient方法,在addColorStop中获取灵感,进行实现
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>高德地图矩形区域清晰示例(从最外到矩形附近渐变)</title>
<style>
#map {
width: 100%;
height: 100vh;
position: relative;
}
#blur-canvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
}
</style>
</head>
<body>
<div id="map"></div>
<canvas id="blur-canvas"></canvas>
<script src="https://webapi.amap.com/maps?v=1.4.15&key=你的 API 密钥"></script>
<script>
var map = new AMap.Map('map', {
center: [116.397428, 39.90923],
zoom: 13
});
var canvas = document.getElementById('blur-canvas');
var ctx = canvas.getContext('2d');
function drawBlurMask() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// 设置矩形位置
var rectX = canvas.width / 2 - 150;
var rectY = canvas.height / 2 - 350;
// 设置矩形大小
var rectWidth = 300;
var rectHeight = 200;
// 设置圆
var blurSize = 1;
var tempCanvas = document.createElement('canvas');
tempCanvas.width = canvas.width;
tempCanvas.height = canvas.height;
var tempCtx = tempCanvas.getContext('2d');
var gradient = tempCtx.createRadialGradient(
canvas.width / 2,
rectY,
Math.max(canvas.width, canvas.height),
rectX + rectWidth / 2,
rectY + rectHeight / 2,
blurSize
);
// gradient.addColorStop(0, 'rgba(100, 255, 100, 1)');
// gradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
// 具体渐变范围,只需修改rgba中的0或1
gradient.addColorStop(0 , 'rgba(100, 255, 100, 1)');
gradient.addColorStop(0.2, 'rgba(100, 255, 100, 1)');
gradient.addColorStop(0.4, 'rgba(100, 255, 100, 1)');
gradient.addColorStop(0.6, 'rgba(100, 255, 100, 1)');
gradient.addColorStop(0.8, 'rgba(100, 255, 100, 0)');
gradient.addColorStop(1 , 'rgba(100, 255, 100, 0)');
tempCtx.fillStyle = gradient;
tempCtx.fillRect(0, 0, tempCanvas.width, tempCanvas.height);
ctx.filter = 'blur(' + blurSize + 'px)';
ctx.drawImage(tempCanvas, 0, 0);
ctx.filter = 'none';
ctx.globalCompositeOperation = 'destination-out';
ctx.fillStyle = 'black';
ctx.fillRect(rectX, rectY, rectWidth, rectHeight);
}
drawBlurMask();
window.addEventListener('resize', drawBlurMask);
</script>
</body>
</html>