<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>写字板</title>
<style type="text/css">
.wrap {
width: 800px;
border: 1px solid gray;
overflow: hidden;
}
#myCanvas {
border: 1px solid gray;
display: block;
float: left;
}
ul {
width: 180px;
list-style: none;
padding: 0;
float: right;
}
span {
width: 30px;
height: 30px;
display: inline-block;
}
#red {
background-color: red;
}
#green {
background-color: green;
}
#yellow {
background-color: yellow;
}
#blue {
background-color: blue;
}
</style>
</head>
<body>
<div class="wrap">
<canvas id="myCanvas" width="600" height="400"></canvas>
<ul>
<li>
<p>画笔颜色</p>
<span id="red"></span>
<span id="green"></span>
<span id="yellow"></span>
<span id="blue"></span>
</li>
<li>
<p>画笔粗细</p>
<input type="button" id="bold" value="变粗" />
<input type="button" id="lighter" value="变细" />
</li>
<li>
<p>操作</p>
<input type="button" id="clear" value="橡皮擦" />
<input type="button" id="empty" value="清空画板" />
</li>
</ul>
</div>
</body>
<script type="text/javascript">
// canvas标签
var canvas = document.getElementById("myCanvas");
// 画笔
var pen = canvas.getContext("2d");
// 橡皮擦按钮
var clearBtn = document.getElementById("clear");
// 清空画布按钮
var emptyBtn = document.getElementById("empty");
// 红色画笔选项标签
var red = document.getElementById("red");
// 绿色画笔选项标签
var green = document.getElementById("green");
// 黄色画笔选项标签
var yellow = document.getElementById("yellow");
// 蓝色画笔选项标签
var blue = document.getElementById("blue");
// 加粗按钮
var boldLine = document.getElementById("bold");
// 变细按钮
var lighterLine = document.getElementById("lighter");
// 默认画笔颜色
var color = 'black';
// 默认画笔粗细
var lineW = 3;
//添加鼠标按下事件
function bei() {
canvas.onmousedown = function(e) {
var even = window.event || e;
// 获取鼠标位置
var x = even.offsetX;
var y = even.offsetY;
pen.beginPath();
pen.strokeStyle = color;
pen.moveTo(x, y);
// 鼠标移动事件
canvas.onmousemove = function(e) {
// 画线逻辑
var even = window.event || e;
// 获取鼠标位置
var x = even.offsetX;
var y = even.offsetY;
pen.lineTo(x, y);
pen.stroke();
}
//添加鼠标松开事件
canvas.onmouseup = function() {
canvas.onmousemove = null;
}
}
}
bei();
//红色画笔点击事件
red.onclick = function() {
color = "red";
}
//绿色画笔点击事件
green.onclick = function() {
color = "green";
}
//黄色画笔点击事件
yellow.onclick = function() {
color = "yellow";
}
//蓝色画笔点击事件
blue.onclick = function() {
color = "blue";
}
//橡皮擦按钮添加点击事件
clearBtn.onclick = function() {
//鼠标按下事件
canvas.onmousedown = function() {
canvas.onmousemove = function(e) {
var even = window.event || e;
// 获取鼠标位置
var x = even.offsetX;
var y = even.offsetY;
pen.clearRect(x,y, 20, 20);
}
}
canvas.onmouseup = function() {
canvas.onmousemove = null;
canvas.onmousedown = null;
bei();
}
}
//清空按钮添加点击事件
emptyBtn.onclick = function() {
//清空画布
pen.clearRect(0, 0, 600, 400);
};
//变粗按钮的点击事件
boldLine.onclick = function() {
pen.lineWidth = pen.lineWidth + lineW;
}
//变细按钮的点击事件
lighterLine.onclick = function() {
pen.lineWidth = pen.lineWidth - lineW;
}
</script>
</html>