<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>画板</title>
<style type="text/css">
#c{
border: 1px solid yellowgreen;
}
span{
/* 使span这个行标签转为行内块状标签*/
display: inline-block;
width: 30px;
height: 30px;
}
#cl1{
background-color: red;
}
#cl2{
background-color: green;
}
#cl3{
background-color: yellow;
}
#cl4{
background-color: gold;
}
</style>
</head>
<body>
<canvas id="c" width="600" height="400"></canvas>
<ul>
<li>
<p>画笔颜色</p>
<span id="cl1"></span>
<span id="cl2"></span>
<span id="cl3"></span>
<span id="cl4"></span>
</li>
<li>
<p>画笔粗细</p>
<button id="btn1" type="button">变粗</button>
<button id="btn2" type="button">变细</button>
</li>
<li>
<p>操作</p>
<button id="btn3" type="button">橡皮擦</button>
<button id="btn4" type="button">清空画板</button>
</li>
</ul>
</body>
<script type="text/javascript">
var c = document.getElementById("c");
var ctx = c.getContext("2d");
// 画笔颜色
var color = "cyan";
// 找到红颜色对应的span
var red = document.getElementById("cl1");
red.onclick = function(){
color = "red";
}
// 找到黄颜色对应的span
var green = document.getElementById("cl2");
green.onclick = function(){
color = "green";
}
// 找到黄颜色对应的span
var yellow = document.getElementById("cl3");
yellow.onclick = function(){
color = "yellow";
}
// 找到金黄色颜色对应的span
var gold = document.getElementById("cl4");
gold.onclick = function(){
color = "gold";
}
// 线条的粗细
var numberWidth = 3;
// 变粗
var changeBig = document.getElementById("btn1");
changeBig.onclick = function(){
numberWidth+=3;
}
// 变细
var changeSmall = document.getElementById("btn2");
changeSmall.onclick = function(){
numberWidth-=3;
if(numberWidth === 3){
numberWidth = 3;
}
}
// 橡皮擦清除功能
function clear(e2){
c.onmousemove = function(e){
// 使用方法.clearRect()清除以鼠标点击处为重心周围20*20的区域
var w = 20;
var h = 20;
var x = e.pageX - c.offsetLeft - w/2;
var y = e.pageY - c.offsetTop - h/2;
ctx.clearRect(x,y,w,h);
}
}
// 橡皮擦
var eraser = document.getElementById("btn3");
eraser.onclick = function(){
// 给画布添加一个按下的事件,做清除功能
c.onmousedown = clear;
// 给画布添加一个鼠标弹起的事件
c.onmouseup = function(){
// 注意:橡皮擦在鼠标点击时移动可以清除,但是当鼠标松开点击时,应将上面鼠标移动清除事件删除;
c.onmousemove = null;
// 并重新赋予鼠标点击事件为画笔事件!
c.onmousedown = drawLine;
}
}
// 清空画板
var clearAll = document.getElementById("btn4");
clearAll.onclick = function(){
// 清空画布
ctx.clearRect(0,0,600,400);
}
// 画笔画画功能
function drawLine(e1){
// 找到按下的位置
var x1 = e1.pageX - c.offsetLeft;
var y1 = e1.pageY - c.offsetTop;
// 画笔移动到鼠标点击处
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.strokeStyle = color;
ctx.lineWidth = numberWidth;
c.onmousemove = function(e2){
// 找到移动到的新点的位置
var x2 = e2.pageX - c.offsetLeft;
var y2 = e2.pageY - c.offsetTop;
ctx.lineTo(x2,y2);
ctx.stroke();
}
}
// 实现鼠标按下移动可以画画
c.onmousedown = drawLine;
// 鼠标松开就不画
c.onmouseup = function(){
c.onmousemove = null;
}
</script>
</html>
2.实现:
通过canvas实现一个画板(具有功能:画笔有四种颜色;画笔粗细可以调整;橡皮擦功能和清空画板功能)
1.源代码: