js 使用canvas制作一个简易的画板

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        canvas {
            border: 1px solid red;
        }
        
        .box {
            width: 510px;
            margin: 0 auto;
        }
    </style>
</head>

<body>
    <div class="box"> <canvas id="canvas" width="500" height="500">
      您的浏览器不支持canvas,请升级为最新版。
    </canvas>
        <br> 线的宽度:
        <select name="" id="wid">
      <option value="1">1px</option>
      <option value="2">2px</option>
      <option value="3">3px</option>
      <option value="4">4px</option>
      <option value="5">5px</option>
      <option value="6">6px</option>
    </select> &nbsp;&nbsp;&nbsp;&nbsp; 线的颜色:
        <input type="color" id="color"> &nbsp;&nbsp;&nbsp;&nbsp;
        <button id="clear">清空</button>
    </div>

    <script>
        /* 获取画布 */
        const canvas = document.getElementById("canvas")
            /* 获取线的宽度 */
        const wid = document.getElementById("wid")
            /* 线的颜色 */
        const color = document.getElementById("color")
            /* 获取清空按钮 */
        const clear = document.getElementById("clear")
        if (canvas.getContext) {
            /* 定义工具 */
            const ctx = canvas.getContext("2d")
                /* 绑定鼠标按下事件 */
            canvas.onmousedown = function(event) {
                    event = event || window.event //兼容写法
                        /* 设置线的宽度 */
                    ctx.lineWidth = wid.value
                        /* 设置现的颜色 */
                    ctx.strokeStyle = color.value
                    ctx.beginPath();
                    /* 设置起点位置 */
                    ctx.moveTo(event.offsetX, event.offsetY)
                        /* 添加鼠标移动事件 */
                    canvas.onmousemove = function(event) {
                        event = event || window.event //兼容写法
                        ctx.lineTo(event.offsetX, event.offsetY)
                            /* 添加描边 */
                        ctx.stroke();
                    }
                }
                /* 添加鼠标解绑事件 */
            window.onmouseup = function() {
                    canvas.onmousemove = null
                }
                /* 设置清空 */
            clear.onclick = function() {
                ctx.clearRect(0, 0, canvas.width, canvas.height)
            }
        }
    </script>
</body>

</html>

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值