HTML5+JavaScript绘制闪烁的网格错觉
闪烁的网格错觉(scintillating grid illusion)是一种视觉错觉,通过简单的黑白方格网格和少量的精心设计,能够使人眼前出现动态变化的效果。
闪烁的栅格错觉,是一种经典的视觉错觉现象。网格错觉是指在由黑白相间的格子组成的图案中,观看者会在网格的交叉点处看到并不实际存在的灰色斑点或黑色圆点的现象。最早由德国心理学家卢迪马尔·赫尔曼(Ludimar Hermann)在1870年发现并报告。
如图所示:
HTML5+JavaScript绘制闪烁的网格错觉,源码如下:
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>闪烁网格错觉</title><style>body {display: flex;justify-content: center;align-items: center;height: 100vh;margin: 0;background-color: #F0FFFF;}canvas {border: 2px solid #333;}</style>
</head>
<body><canvas id="illusion" width="400" height="400"></canvas><script>const canvas = document.getElementById('illusion');const ctx = canvas.getContext('2d');const gridSize = 10;const cellSize = canvas.width / gridSize;function drawGrid() {// 设置黑色背景ctx.fillStyle = 'black';ctx.fillRect(0, 0, canvas.width, canvas.height);// 绘制灰色网格线#888ctx.strokeStyle = '#696969';ctx.lineWidth = 10;// 绘制竖线和横线for (let i = 1; i < gridSize; i++) {const pos = i * cellSize;// 竖线ctx.beginPath();ctx.moveTo(pos, 0);ctx.lineTo(pos, canvas.height);ctx.stroke();// 横线ctx.beginPath();ctx.moveTo(0, pos);ctx.lineTo(canvas.width, pos);ctx.stroke();}// 在交叉点绘制白色圆点ctx.fillStyle = 'white';for (let x = cellSize; x < canvas.width; x += cellSize) {for (let y = cellSize; y < canvas.height; y += cellSize) {ctx.beginPath();ctx.arc(x, y, 5, 0, Math.PI * 2);ctx.fill();}}}drawGrid();</script>
</body>
</html>