canvas制作一个简单绘画板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0,user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>能回话的应用</title>
<style>
* {
padding: 0;
margin: 0;
}
canvas {
border: solid 1px black;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 800px;
height: 600px;
}
</style>
</head>
<body>
颜色:<input type="color" id="color">
粗细:<input type="number" max="10" min="1" id="width">
<canvas id="cv" width="800" height="600">
您的浏览器不支持canvas!
</canvas>
</body>
<script>
var cv = document.getElementById("cv");
var ct = cv.getContext("2d");
//记录起点坐标
var lastX;
var lasty;
var flag = false; //是否绘制
//鼠标的时间处理
cv.onmousedown = function(e) {
flag = true; //开启绘制标识
//初始化起点坐标
lastX = e.offsetX;
lasty = e.offsetY;
}
cv.onmousemove = function(e) {
if (flag) {
//绘制实线
ct.beginPath();
ct.moveTo(lastX, lasty);
ct.lineTo(e.offsetX, e.offsetY);
ct.stroke();
//更新起点坐标
lastX = e.offsetX;
lasty = e.offsetY;
}
}
cv.onmouseup = function(e) {
flag = false;
}
// 改变画笔的颜色
document.getElementById("color").onchange = function() {
console.log(1);
ct.strokeStyle = this.value || 'black';
};
//改变画笔的粗细
document.getElementById("width").onchange = function() {
ct.lineWidth = this.value || 'black';
};
</script>
</html>