js实现方块
使用Canvas绘制方块
通过HTML5的Canvas API可以轻松绘制方块。创建一个canvas元素,获取其上下文后使用fillRect方法绘制矩形。
<canvas id="canvas" width="200" height="200"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 100, 100); // x, y, width, height
</script>
使用CSS和DOM创建方块
通过JavaScript动态创建div元素,并为其添加CSS样式来实现方块效果。
const square = document.createElement('div');
square.style.width = '100px';
square.style.height = '100px';
square.style.backgroundColor = 'red';
document.body.appendChild(square);
使用SVG绘制方块
利用SVG的rect元素结合JavaScript动态生成方块。
<svg id="svg" width="200" height="200"></svg>
<script>
const svg = document.getElementById('svg');
const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect.setAttribute('x', '50');
rect.setAttribute('y', '50');
rect.setAttribute('width', '100');
rect.setAttribute('height', '100');
rect.setAttribute('fill', 'green');
svg.appendChild(rect);
</script>
使用WebGL绘制3D方块
通过WebGL可以创建更复杂的3D方块效果。以下是一个基础示例。
<canvas id="glCanvas" width="500" height="500"></canvas>
<script>
const canvas = document.getElementById('glCanvas');
const gl = canvas.getContext('webgl');
if (!gl) {
alert('WebGL not supported');
}
const vertices = [
// Front face
-0.5, -0.5, 0.5,
0.5, -0.5, 0.5,
0.5, 0.5, 0.5,
-0.5, 0.5, 0.5,
];
const vertexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, `
attribute vec3 position;
void main() {
gl_Position = vec4(position, 1.0);
}
`);
gl.compileShader(vertexShader);
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, `
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
`);
gl.compileShader(fragmentShader);
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
gl.useProgram(shaderProgram);
const position = gl.getAttribLocation(shaderProgram, 'position');
gl.enableVertexAttribArray(position);
gl.vertexAttribPointer(position, 3, gl.FLOAT, false, 0, 0);
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLE_FAN, 0, 4);
</script>
使用CSS动画让方块移动
为方块添加CSS动画效果,使其能够移动。
const square = document.createElement('div');
square.style.width = '100px';
square.style.height = '100px';
square.style.backgroundColor = 'purple';
square.style.position = 'absolute';
square.style.left = '0px';
document.body.appendChild(square);
let pos = 0;
function animate() {
pos += 1;
square.style.left = pos + 'px';
if (pos < 300) {
requestAnimationFrame(animate);
}
}
animate();






