html代码
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>kc_homework_10</title> </head> <body style="text-align: center;"> <canvas id="myCanvas" width="200" height="400"></canvas> </body> </html>
JavaScript代码(写在body里面)
<script> var c = document.getElementById("myCanvas"); var ctx = c.getContext("2d"); // 1顶部三角形 // beginPath() 方法开始一条路径,或重置当前的路径。 ctx.beginPath(); // moveTo() 方法把路径移动到画布中的指定点,不创建线条。 ctx.moveTo(100, 0); // lineTo() 方法添加一个新点,然后创建从该点到画布中最后指定点的线条(该方法并不会创建线条)。 ctx.lineTo(200, 100); ctx.lineTo(0, 100); // stroke() 方法会实际地绘制出通过 moveTo() 和 lineTo() 方法定义的路径。 ctx.stroke(); // strokeStyle 属性设置或返回用于笔触的颜色、渐变或模式。 ctx.strokeStyle = "lightgreen"; // fillStyle 属性设置或返回用于填充绘画的颜色、渐变或模式。 ctx.fillStyle = "green"; // fill() 方法填充当前的图像(路径)。 ctx.fill(); // 2红色矩形 ctx.beginPath(); ctx.rect(25, 100, 150, 150);//(坐标x,y,宽,高)的矩形 ctx.strokeStyle = "red"; ctx.fillStyle = "red"; ctx.fill(); // 3窗户矩形 ctx.beginPath(); ctx.rect(45, 120, 30, 80); ctx.strokeStyle = "black"; ctx.fillStyle = "white"; ctx.fill(); ctx.stroke(); ctx.beginPath(); ctx.rect(75, 120, 30, 80); ctx.strokeStyle = "black"; ctx.fillStyle = "white"; ctx.fill(); ctx.stroke(); // 4门口矩形 ctx.beginPath(); ctx.rect(120, 140, 40, 111); ctx.strokeStyle = "yellow"; ctx.fillStyle = "yellow"; ctx.fill(); ctx.beginPath(); ctx.moveTo(120, 251); ctx.lineTo(120, 139); ctx.lineTo(161, 139); ctx.lineTo(161, 251); ctx.strokeStyle = "black"; ctx.stroke(); // 5文字 ctx.beginPath(); ctx.font = "30px STCaiyun"; ctx.fillText("我的家", 60, 285); </script>