Home > Web Front-end > H5 Tutorial > HTML5 implements a simple online drawing board

HTML5 implements a simple online drawing board

王林
Release: 2020-12-04 16:18:33
forward
10679 people have browsed it

HTML5 implements a simple online drawing board

Let’s take a look at the implementation first:

(Recommended tutorial: h5)

HTML5 implements a simple online drawing board

The implementation code is as follows:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <canvas id="canvas" width="600" height="600"></canvas>
        <script type="text/javascript">
            var c = document.getElementById(&#39;canvas&#39;);
            var ctx = c.getContext(&#39;2d&#39;);

            //画一个黑色矩形
            ctx.fillStyle = &#39;black&#39;;
            ctx.fillRect(0,0,600,300);

            //按下标记
            var onoff = false;
            var oldx = -10;
            var oldy = -10;

            //设置颜色
            var linecolor = &#39;white&#39;;

            //设置线宽
            var linw = 4;

            //添加鼠标移动事件
            canvas.addEventListener(&#39;mousemove&#39;,draw,true);

            //添加鼠标按下事件
            canvas.addEventListener(&#39;mousedown&#39;,down,false);

            //添加鼠标弹起事件
            canvas.addEventListener(&#39;mouseup&#39;,up,false);

            function down(event) {
                onoff = true;
                oldx = event.pageX-10;
                oldy = event.pagey-10;
            }

            function up() {
                onoff = false;
            }

            function draw(event) {
                if(onoff == true) {
                    var newx = event.pageX-10;
                    var newy = event.pageY-10;
                    ctx.beginPath();
                    ctx.moveTo(oldx,oldy);
                    ctx.lineTo(newx,newy);
                    ctx.strokeStyle = linecolor;
                    ctx.lineCap = &#39;round&#39;;
                    ctx.stroke();

                    oldx = newx;
                    oldy = newy;
                }
            }
        </script>
    </body>
</html>
Copy after login

Free learning video sharing: html video tutorial

The above is the detailed content of HTML5 implements a simple online drawing board. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template