Introduction

125 阅读1分钟

boilerplate code

第一节课的简单的canvas使用的介绍课程,使用默认的boilerplate code模板代码如下, 使用CanvasRenderingContext2D interface接口对象。

可以通过 code . 通过vscode打开当前文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        window.onload = function() {
            // reference
            const canvas = document.getElementById("canvas"),
            //  CanvasRenderingContext2D interface
                  context = canvas.getContext("2d"),
                  width = canvas.width = window.innerWidth,
                  height = canvas.height = window.innerHeight;
    </script>
</head>
<body>
    <canvas id="canvas"></canvas>
</body>
</html>

此时遇见了scroll bar 滚动条的问题, 是因为因为canvas默认的display是inline。还有一个是margin的问题, 把边距修改成0即可。在css文件中修改即可。

 <style>
 html, body {
     margin: 0;
 }
 canvas {
     display: block;
 }
</style>

简单矩形对象

使用fillRect()填充一个矩形对象

// 填充一个矩形
context.fillRect(0, 0, width, height)

生成随机的一百条直线

通过Math.random()控制坐标生成随机的一百条直线

for (let i = 0; i < 100; i+=1) {
   context.beginPath();   // Start a new path
   context.moveTo(Math.random() * width, Math.random() * height)  // Move the pen to ()
   context.lineTo(Math.random() * width, Math.random() * height)  // Draw a line to ()
   context.stroke();     // Render the path
}

Vocabulary Summary

introduction

math
canves
boilerplate code 样板代码

Reference