1.采用canvas绘图
<canvas id="canvas" width="800" height="600"></canvas>
<script>
// 获取画布元素
var canvas = document.getElementById('canvas')
// 获取二维绘图对象
var ctx = canvas.getContext("2d")
// 设置线的宽度
ctx.lineWidth = 6
// 设置线的颜色
ctx.strokeStyle = 'red'
// 填充的颜色
ctx.fillStyle = 'pink'
ctx.moveTo(10, 10) // 起点
ctx.lineTo(200, 10) // 下一个点
ctx.lineTo(200, 300) // 下一个点
ctx.lineTo(10, 10) // 下一个点
ctx.stroke() // fill()执行填充色,stroke()执行
ctx.fill()
// 重新绘制
ctx.beginPath()
ctx.moveTo(300, 10)
ctx.lineTo(300, 50)
ctx.lineTo(400, 50)
ctx.closePath() // 闭合
ctx.stroke()
</script>
2. canvas实现绘图板
<canvas id="canvas" width="800" height="600"></canvas> <script> // 获取画布元素 var canvas = document.getElementById('canvas') // 获取二维绘图对象 var ctx = canvas.getContext("2d") // 设置线的宽度 ctx.lineWidth = 3 // 设置线的颜色 ctx.strokeStyle = 'red' // 绘图标记位 let flag = false // 实现绘图板 // 按下 canvas.onmousedown = function(e) { flag = true ctx.beginPath() } canvas.onmousemove = function(e) { if(!flag) return ctx.lineTo(e.clientX, e.clientY) // 下一点 ctx.stroke() } // 松开 canvas.onmouseup = function(e) { flag = false } </script>