js实现方块
使用HTML和CSS创建方块
在HTML中创建一个方块可以通过<div>元素实现,结合CSS设置宽度、高度和背景颜色。以下是一个基本示例:
<div class="square"></div>
.square {
width: 100px;
height: 100px;
background-color: #3498db;
}
使用JavaScript动态生成方块
通过JavaScript动态创建方块并添加到DOM中:
const square = document.createElement('div');
square.style.width = '100px';
square.style.height = '100px';
square.style.backgroundColor = '#e74c3c';
document.body.appendChild(square);
实现可交互方块
为方块添加点击事件,改变其颜色或位置:

square.addEventListener('click', () => {
square.style.backgroundColor = '#2ecc71';
square.style.transform = 'translateX(50px)';
});
使用Canvas绘制方块
通过Canvas API绘制一个方块:
const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#9b59b6';
ctx.fillRect(10, 10, 100, 100);
方块动画效果
使用CSS动画或JavaScript实现方块移动:

.square {
animation: move 2s infinite alternate;
}
@keyframes move {
from { transform: translateX(0); }
to { transform: translateX(200px); }
}
或者使用JavaScript:
let pos = 0;
function animate() {
pos += 1;
square.style.left = pos + 'px';
requestAnimationFrame(animate);
}
animate();
响应式方块
通过CSS使方块大小随窗口变化:
.square {
width: 10vw;
height: 10vw;
max-width: 200px;
max-height: 200px;
}






