html样式
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style type="text/css">
canvas {
border: 1px solid #ccc;
}
</style>
</head>
<body>
<input id="colorSelect" type="color" name="" value="" placeholder="">
<br>
<input type="submit" name="" value="清空画板" onclick="qingkong()">
<br>
<canvas width="500" height="500" id="canvas">
您的浏览器不支持
</canvas>
</body>
javascript代码
// 获取Input的id
var selector = document.getElementById("colorSelect");
// 声明color的全局变量
var color = null;
// 获取color的颜色
selector.onchange = function(){
color = this.value;
}
var canvas = document.getElementById("canvas");
var cxt = canvas.getContext("2d");
// 鼠标按下
canvas.onmousedown = function(e){
// 获取canvas画面上的x y 轴
var x = e.clientX - canvas.offsetLeft;
var y = e.clientY - canvas.offsetTop;
cxt.beginPath();
cxt.moveTo(x,y);
canvas.onmousemove = function(e){
var x = e.clientX - canvas.offsetLeft;
var y = e.clientY - canvas.offsetTop;
cxt.lineTo(x,y);
cxt.strokeStyle=color;
cxt.stroke();
}
// 鼠标抬起事件 把上一个的move的事件清空
canvas.onmouseup = function(){
canvas.onmousemove = null;
}
}
// 一键清空按钮
function qingkong(){
cxt.clearRect(0,0,500,500);
console.log(11);
}
网友评论