用纯JS画一只狗包括创建元素 
时间: 2023-05-31 21:05:04 浏览: 19
很高兴为您提供帮助。以下是一个简单的纯JS绘制狗的示例,包括创建元素:
HTML:
```html
<!DOCTYPE html>
<html>
<head>
<title>Dog Drawing</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script src="script.js"></script>
</body>
</html>
```
JavaScript:
```javascript
// 获取canvas元素
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 画狗的头部
ctx.beginPath();
ctx.arc(200, 100, 80, 0, 2 * Math.PI);
ctx.fillStyle = 'brown';
ctx.fill();
ctx.strokeStyle = 'black';
ctx.stroke();
// 画狗的眼睛
ctx.beginPath();
ctx.arc(170, 80, 10, 0, 2 * Math.PI);
ctx.fillStyle = 'white';
ctx.fill();
ctx.stroke();
ctx.beginPath();
ctx.arc(170, 80, 3, 0, 2 * Math.PI);
ctx.fillStyle = 'black';
ctx.fill();
ctx.beginPath();
ctx.arc(230, 80, 10, 0, 2 * Math.PI);
ctx.fillStyle = 'white';
ctx.fill();
ctx.stroke();
ctx.beginPath();
ctx.arc(230, 80, 3, 0, 2 * Math.PI);
ctx.fillStyle = 'black';
ctx.fill();
// 画狗的耳朵
ctx.beginPath();
ctx.moveTo(120, 70);
ctx.lineTo(160, 50);
ctx.lineTo(170, 80);
ctx.fillStyle = 'brown';
ctx.fill();
ctx.stroke();
ctx.beginPath();
ctx.moveTo(280, 70);
ctx.lineTo(240, 50);
ctx.lineTo(230, 80);
ctx.fillStyle = 'brown';
ctx.fill();
ctx.stroke();
// 画狗的身体
ctx.beginPath();
ctx.arc(200, 300, 120, 0, 2 * Math.PI);
ctx.fillStyle = 'brown';
ctx.fill();
ctx.strokeStyle = 'black';
ctx.stroke();
// 画狗的四条腿
ctx.beginPath();
ctx.moveTo(120, 260);
ctx.lineTo(120, 350);
ctx.lineTo(160, 350);
ctx.lineTo(160, 260);
ctx.fillStyle = 'brown';
ctx.fill();
ctx.stroke();
ctx.beginPath();
ctx.moveTo(280, 260);
ctx.lineTo(280, 350);
ctx.lineTo(240, 350);
ctx.lineTo(240, 260);
ctx.fillStyle = 'brown';
ctx.fill();
ctx.stroke();
ctx.beginPath();
ctx.moveTo(170, 320);
ctx.lineTo(170, 390);
ctx.lineTo(200, 390);
ctx.lineTo(200, 320);
ctx.fillStyle = 'brown';
ctx.fill();
ctx.stroke();
ctx.beginPath();
ctx.moveTo(200, 320);
ctx.lineTo(200, 390);
ctx.lineTo(230, 390);
ctx.lineTo(230, 320);
ctx.fillStyle = 'brown';
ctx.fill();
ctx.stroke();
```
这段代码使用了canvas绘图API来绘制狗的各个部分。注释已经解释了每个绘图操作的含义。此外,还可以使用JS动态创建canvas元素和其他HTML元素。例如,以下代码将创建一个画布和一个按钮:
```javascript
// 创建canvas元素
const canvas = document.createElement('canvas');
canvas.width = 400;
canvas.height = 400;
canvas.id = 'canvas';
document.body.appendChild(canvas);
// 创建按钮元素
const button = document.createElement('button');
button.innerText = 'Click me';
button.onclick = function() {
alert('Button clicked!');
};
document.body.appendChild(button);
```
希望这能够帮助到您。
相关推荐


















