html5的canvas写一个简单的画板程序

html5的canvas写一个简单的画板程序


思路:

获得按下时候的坐标ctx.moveTo(e.clientX-10,e.clientY-10)然后鼠标移动的时候就不断的画线,!isDown||ctx.lineTo(e.clientX-10, e.clientY-10, 5, 5)鼠标放开的时候,自然就要吧isDown设置为false了。
然后就总结一下画线的关键步骤好了。
第一步是取得画布。
第二步是开始画线。beginPath()
第三步是移动线条moveTo(),lineTo()。
第四步就是画线stroke()。


代码:

<!DOCTYPE html>

<html lang="en">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />

<title>画线例子</title>

<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js?ver=1.4.2"></script>

<script type="text/javascript">

        window.onload = function()

        {

                if(document.getElementById('c'))

                {

                         var isDown = false;//判断是否按下

                         var ctx = $('#c').get(0).getContext('2d');//取得画布

                         ctx.strokeStyle = 'black';//线条颜色

                         ctx.beginPath();//开始画线

                         $('body')

                         .mousedown(function(e){

                                isDown = true;

                                ctx.moveTo(e.clientX-10,e.clientY-10);//画笔拿起放到哪一点

                         })

                         .mousemove(function(e){

                                !isDown||ctx.lineTo(e.clientX-10, e.clientY-10, 5, 5); //画笔画到哪一点

                                 ctx.stroke();//画线函数

                         })

                         .mouseup(function(){

                                isDown = false;

                         });

                }else{alert('ss');}

        }

</script>

<style type="text/css">

        #c{ border:1px solid black;}

</style>

</head>

<body>

<canvas id="c" width="900" height="600">

        你的浏览器不支持canvas标签,请使用firefox和chrome浏览器

</canvas>

</body>

</html>


效果图:


原文地址:https://www.cnblogs.com/javawebsoa/p/2994101.html