| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- <style>
- #canvas {
- /* 背景颜色 */
- background-color: black;
- }
- </style>
- </head>
- <body>
- <!-- 画布元素 -->
- <canvas id="canvas" width="500" height="500"></canvas>
- <script>
- // 获取元素
- var canvas = document.querySelector("#canvas");
- // 获取上下文
- var ctx = canvas.getContext("2d");
- // 设置线的颜色
- ctx.strokeStyle = "white";
- // 设置线的宽度
- ctx.lineWidth = 2;
- // 为画布绑定鼠标按下事件
- canvas.onmousedown = function (event) {
- // 开始绘制 beginPath
- ctx.beginPath();
- // moveTo 移动到指定位置(落笔点)
- ctx.moveTo(event.clientX, event.clientY);
- // 绑定鼠标移动事件
- canvas.onmousemove = function (e) {
- // lineTo 绘制一条线到指定位置
- ctx.lineTo(e.clientX, e.clientY);
- // stroke 绘制线
- ctx.stroke();
- }
- }
- // 为画布绑定鼠标松开事件
- canvas.onmouseup = function () {
- // 绘制完成,清除鼠标移动事件
- canvas.onmousemove = null;
- }
- </script>
- </body>
- </html>
|