最近了解到html5强大的绘图功能让我惊奇,于是,写了个小玩意---涂鸦板,能实现功能有:画画,改色,调整画笔大小

html5的绘图可以分为点,线,面,圆,图片等,点和线,这可是所有平面效果的基点,有了这两个东西,没有画不出来的东西,只有想不到的算法。

先上代码了:

html

XML/HTML Code 复制内容到剪贴板 <body style="cursor:pointer">     < canvas   id = "mycavas"   width = "1024"   height = "400"   style = "border:solid 4px #000000" > </ canvas > <!--画布-->             < input   type = "color"   id = "color1"   name = "color1" /> <!--设色器-->             < output   name = "a"   for = "color1"   onforminput = "innerHTML=color1.value" > </ output >              < input   type = "range"   name = "points"   id = "size"   min = "5"   max = "20"   /> <!--拖动条-->    </ body >      

效果:

好了,一个简陋的画图界面就搞好啦,下面开始写一些画线的代码 

JavaScript Code 复制内容到剪贴板 $.Draw = {};    $.extend($.Draw, {        D2:  "" ,        CX: "" ,        Box:  "mycavas" , //画布id        BoxObj: function (){ //画布对象             this .CX=document.getElementById( this .Box);        },        D2: function (){ //2d绘图对象            this .D2 =  this .CX.getContext( "2d" );        },        Cricle:  function  (x, y, r, color) { //画圆             if  ( this .D2) {                 this .D2.beginPath();                 this .D2.arc(x, y, r, 0, Math.PI * 2,  true );                 this .D2.closePath();                 if  (color) {                     this .D2.fillStyle = color;                }                 this .D2.fill();            }        },        init:  function  () { //初始化             this .BoxObj();             this .D2();        }       })      

相信这里的简单代码大家都看得懂,主要就是创建了一个对象,包含创建画布,创建2d对象,画圆方法,和对象初始化方法。

接下里前台html页面来调用这个对象/p>

看代码:

JavaScript Code 复制内容到剪贴板 var color = "#000000";//初始化颜色             var  size = 5; //初始化尺寸            document.getElementById( 'color1' ).onchange =  function  () {                color =  this .value;            };            document.getElementById( 'size' ).onchange =  function  () {                size =  this .value;            };            $.Draw.init(); //初始化             var  tag =  false ; //控制鼠标当前状态并起到开启油墨开关的作用             var  current = {}; //存储鼠标按下时候的点            document.onmousedown =  function  (option) { //鼠标按下事件                current.x = option.x;                current.y = option.y;                $.Draw.Cricle(option.x, option.y, size, color);                tag =  true ;            }            document.onmouseup =  function  () { //鼠标抬起事件                tag =  false ;            }            document.onmousemove =  function  (option) { //鼠标移动事件                 if  (tag) {                     if  (size >= 0) {                        $.Draw.Cricle(option.x, option.y, size, color);                    }                 }            }   

这段代码主要有如下几个意思

1.捕获颜色空间和拖动条控件的change事件,从而获取对应的颜色和尺寸的数值,存储下来供下面画线用

2.初始化画图对象

3.捕获鼠标的按下,抬起和移动事件,关键在一个开关可以控制油墨

好了,一个简单的涂鸦板就好了,上我的书法:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

原文链接:http://www.cnblogs.com/bob1314/p/3830220.html