PHP前端开发

html5实现一个简单的在线画板

百变鹏仔 2个月前 (10-17) #H5教程
文章标签 在线

我们先来看看实现效果:

(推荐教程:h5)

实现代码如下:

立即学习“前端免费学习笔记(深入)”;

<!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>

免费学习视频分享:html视频教程