HTML5两个画布如何弄,使用HTML5将两个画布方块设置到画布的中心(Set two canvas squares to the center of a canvas with HTML5)...
时间: 2023-12-10 14:37:58 浏览: 156
您可以使用以下步骤在HTML5中将两个画布方块设置到画布的中心:
1. 创建两个画布元素,并设置它们的宽度和高度。
```html
<canvas id="canvas1" width="200" height="200"></canvas>
<canvas id="canvas2" width="200" height="200"></canvas>
```
2. 获取画布元素的上下文,以便可以在画布上绘制图形。
```javascript
var canvas1 = document.getElementById("canvas1");
var ctx1 = canvas1.getContext("2d");
var canvas2 = document.getElementById("canvas2");
var ctx2 = canvas2.getContext("2d");
```
3. 计算画布的中心点坐标。
```javascript
var centerX = canvas1.width / 2;
var centerY = canvas1.height / 2;
```
4. 在画布上绘制一个方块,并将其定位到画布的中心。
```javascript
var squareSize = 50;
ctx1.fillStyle = "blue";
ctx1.fillRect(centerX - squareSize/2, centerY - squareSize/2, squareSize, squareSize);
```
5. 重复步骤4,但在第二个画布上绘制红色方块。
```javascript
ctx2.fillStyle = "red";
ctx2.fillRect(centerX - squareSize/2, centerY - squareSize/2, squareSize, squareSize);
```
完整的HTML代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<title>Two Canvas Squares</title>
</head>
<body>
<canvas id="canvas1" width="200" height="200"></canvas>
<canvas id="canvas2" width="200" height="200"></canvas>
<script>
var canvas1 = document.getElementById("canvas1");
var ctx1 = canvas1.getContext("2d");
var canvas2 = document.getElementById("canvas2");
var ctx2 = canvas2.getContext("2d");
var centerX = canvas1.width / 2;
var centerY = canvas1.height / 2;
var squareSize = 50;
ctx1.fillStyle = "blue";
ctx1.fillRect(centerX - squareSize/2, centerY - squareSize/2, squareSize, squareSize);
ctx2.fillStyle = "red";
ctx2.fillRect(centerX - squareSize/2, centerY - squareSize/2, squareSize, squareSize);
</script>
</body>
</html>
```
阅读全文