js实现积木
实现积木效果的 JavaScript 方法
使用 JavaScript 实现积木效果通常涉及 DOM 操作和 CSS 样式的动态控制。以下是几种常见的实现方式:
拖拽积木
通过 HTML5 的拖拽 API 实现积木的拖放功能:
document.addEventListener('DOMContentLoaded', function() {
const blocks = document.querySelectorAll('.block');
blocks.forEach(block => {
block.setAttribute('draggable', true);
block.addEventListener('dragstart', function(e) {
e.dataTransfer.setData('text/plain', this.id);
});
});
const container = document.getElementById('container');
container.addEventListener('dragover', function(e) {
e.preventDefault();
});
container.addEventListener('drop', function(e) {
e.preventDefault();
const id = e.dataTransfer.getData('text/plain');
const draggedBlock = document.getElementById(id);
this.appendChild(draggedBlock);
});
});
随机生成积木
动态创建积木元素并设置随机样式:
function createRandomBlocks(count) {
const container = document.getElementById('container');
for(let i = 0; i < count; i++) {
const block = document.createElement('div');
block.className = 'block';
// 随机位置和颜色
block.style.left = `${Math.random() * 80}%`;
block.style.top = `${Math.random() * 80}%`;
block.style.backgroundColor = `hsl(${Math.random() * 360}, 70%, 60%)`;
container.appendChild(block);
}
}
积木碰撞检测
实现积木之间的物理碰撞效果:
class Block {
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.vx = Math.random() * 2 - 1;
this.vy = Math.random() * 2 - 1;
}
update(blocks) {
this.x += this.vx;
this.y += this.vy;
// 边界检测
if(this.x <= 0 || this.x + this.width >= canvas.width) {
this.vx *= -1;
}
if(this.y <= 0 || this.y + this.height >= canvas.height) {
this.vy *= -1;
}
// 碰撞检测
blocks.forEach(block => {
if(block !== this && this.checkCollision(block)) {
[this.vx, block.vx] = [block.vx, this.vx];
[this.vy, block.vy] = [block.vy, this.vy];
}
});
}
checkCollision(block) {
return this.x < block.x + block.width &&
this.x + this.width > block.x &&
this.y < block.y + block.height &&
this.y + this.height > block.y;
}
}
配套 CSS 样式
积木的基本样式定义:
.block {
position: absolute;
width: 50px;
height: 50px;
background-color: #3498db;
cursor: move;
user-select: none;
transition: transform 0.2s;
}
.block:hover {
transform: scale(1.1);
z-index: 10;
}
#container {
position: relative;
width: 100%;
height: 500px;
border: 1px solid #ccc;
overflow: hidden;
}
进阶功能实现
积木堆叠系统
实现积木的堆叠和组合功能:
function setupStacking() {
let currentZIndex = 1;
document.querySelectorAll('.block').forEach(block => {
block.addEventListener('mousedown', function() {
this.style.zIndex = currentZIndex++;
});
});
}
积木旋转功能
添加积木旋转交互:

function setupRotation() {
document.querySelectorAll('.block').forEach(block => {
let rotation = 0;
block.addEventListener('dblclick', function() {
rotation += 15;
this.style.transform = `rotate(${rotation}deg)`;
});
});
}
以上代码提供了积木效果的基本实现框架,可以根据具体需求进行调整和扩展。






