(五)实现画笔和橡皮的功能

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>鼠标画线和方块移动</title>
</head>
<style>
* {margin: 0;padding: 0;}
body {background-color: #000;}
#c1 {background-color: #fff}
.active {background-color: red;color: #fff}
</style>
<body>
<canvas id="c1" width="400" height="400"></canvas>
<input class="active" type="button" value="画笔">
<input type="button" value="橡皮擦">
<script>
var oC = document.getElementById('c1');
var aInput = document.getElementsByTagName("input");
var num = 0;
for(var i=0;i<aInput.length;i++) {
aInput[i].index = i;
aInput[i].onclick = function () {
for(var j= 0;j<aInput.length;j++) {
aInput[j].className = "";
}
this.className = "active";
num = this.index;
}
}
var ctx = oC.getContext("2d");
oC.onmousedown = function(ev) {
var x = ev.pageX - oC.offsetLeft;
var y = ev.pageY - oC.offsetTop;
ctx.beginPath();
ctx.moveTo(x,y);
oC.onmousemove = function(ev) {
var x = ev.pageX - oC.offsetLeft;
var y = ev.pageY - oC.offsetTop;
if(num ==0) {
ctx.lineTo(x,y);
ctx.stroke();
} else if(num ==1) {
ctx.clearRect(x,y,20,20);
}
};
oC.onmouseup = function (ev) {
oC.onmousemove = null;
oC.onmouseup = null;
ctx.closePath();
};
return false;
}
</script>
</body>
</html>

 

posted @ 2018-08-02 14:05  狗尾草的博客  阅读(280)  评论(0编辑  收藏  举报