js实现方块
使用HTML和CSS创建方块
在HTML中创建一个方块可以通过<div>元素结合CSS样式实现。以下是一个简单的示例:
<div class="square"></div>
.square {
width: 100px;
height: 100px;
background-color: blue;
}
使用JavaScript动态生成方块
通过JavaScript动态创建方块并添加到DOM中:
// 创建方块元素
const square = document.createElement('div');
square.style.width = '100px';
square.style.height = '100px';
square.style.backgroundColor = 'red';
// 添加到页面
document.body.appendChild(square);
实现可交互的方块
添加事件监听器使方块可点击或可拖动:
const square = document.createElement('div');
square.style.width = '100px';
square.style.height = '100px';
square.style.backgroundColor = 'green';
square.style.cursor = 'pointer';
// 点击改变颜色
square.addEventListener('click', () => {
square.style.backgroundColor = 'yellow';
});
document.body.appendChild(square);
使用Canvas绘制方块
通过Canvas API绘制方块:
<canvas id="canvas" width="200" height="200"></canvas>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 绘制红色方块
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 100);
方块动画效果
使用JavaScript实现方块移动动画:
const square = document.createElement('div');
square.style.width = '50px';
square.style.height = '50px';
square.style.backgroundColor = 'purple';
square.style.position = 'absolute';
document.body.appendChild(square);
let pos = 0;
function animate() {
pos++;
square.style.left = pos + 'px';
if (pos < 200) {
requestAnimationFrame(animate);
}
}
animate();
响应式方块
创建随窗口大小变化的方块:

const square = document.createElement('div');
square.style.width = '20vw';
square.style.height = '20vw';
square.style.backgroundColor = 'orange';
document.body.appendChild(square);






