Canvas系列之七彩画板

以前总是在画画软件上画画,今天自己也写了一个

七彩画板当然要有七中颜色了,你也可以获取更多地颜色

先让我们看看效果如何:

画板

点击画笔开始绘画,点击颜色选择画笔的颜色,点击橡皮擦清除

结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<div class="wrap">
<canvas id="canvas" width="600" height="500">画笔写字</canvas>
<button>橡皮擦</button>
<button>画笔</button>
<div class="font"><h3><br/></h3></div>
<ul>
<li style="background-color:red;margin-left:100px;"></li>
<li style="background-color:orange"></li>
<li style="background-color:yellow"></li>
<li style="background-color:green"></li>
<li style="background-color:cyan"></li>
<li style="background-color:blue"></li>
<li style="background-color:purple"></li>
</ul>
</div>

先让我们获取元素 这里使用了ES6的写法

如果不了解,可参考:lxjwlt’s blog

var canvas=document.querySelector('#canvas');
var ctx=canvas.getContext('2d');

var font=document.querySelector('.font');
var btn=document.querySelectorAll('button');
var li=document.querySelectorAll('li');

接下来就是画笔以及画笔的颜色

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
btn[1].onclick=function(){
font.style.display='none';
canvas.style.cursor="url('pen.png'),pointer";
//选择画笔的颜色
var color='';
for(var i=0;i<li.length;i++){
li[i].onclick=function(){
color=this.style.backgroundColor;
console.log(color)
}
}
canvas.onmousedown=function(){
window.onmousemove=function(event){
ctx.fillStyle=color;
ctx.fillRect(event.offsetX,event.offsetY,5,5);
}
}
canvas.onmouseup = function(){
window.onmousemove=function(){}
}
}

下面让我们完成橡皮擦

```js

    btn[0].onclick=function(){
    canvas.onmousedown=function(){
        window.onmousemove=function(event){
            ctx.clearRect(event.offsetX,event.offsetY,20,20);
        }
    }
    canvas.onmouseup = function(){
        window.onmousemove=function(){}
    }
    canvas.style.cursor="url('xpc.cur'),pointer";
    }
```        

画板已经完成,查看源码请前往:my github,希望对你有所帮助

很惭愧<br><br>只做了一点微小的工作<br>谢谢大家