最近了解到html5強(qiáng)大的繪圖功能讓我驚奇,于是,寫了個(gè)小玩意---涂鴉板,能實(shí)現(xiàn)功能有:畫畫,改色,調(diào)整畫筆大小
html5的繪圖可以分為點(diǎn),線,面,圓,圖片等,點(diǎn)和線,這可是所有平面效果的基點(diǎn),有了這兩個(gè)東西,沒(méi)有畫不出來(lái)的東西,只有想不到的算法。
XML/HTML Code復(fù)制內(nèi)容到剪貼板
- <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復(fù)制內(nèi)容到剪貼板
- $.Draw = {};
- $.extend($.Draw, {
- D2: "",
- CX:"",
- Box: "mycavas",
- BoxObj:function(){
- this.CX=document.getElementById(this.Box);
- },
- D2:function(){
- 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();
- }
-
- })
-
相信這里的簡(jiǎn)單代碼大家都看得懂,主要就是創(chuàng)建了一個(gè)對(duì)象,包含創(chuàng)建畫布,創(chuàng)建2d對(duì)象,畫圓方法,和對(duì)象初始化方法。
JavaScript Code復(fù)制內(nèi)容到剪貼板
- 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.捕獲顏色空間和拖動(dòng)條控件的change事件,從而獲取對(duì)應(yīng)的顏色和尺寸的數(shù)值,存儲(chǔ)下來(lái)供下面畫線用