Canvas是HTML5中非常重要的一个更新亮点,画布,替代Flash的!制作动画、制作游戏。 现在我们使用canvas的基础知识来制作一个简单的画板.
详细的过程与思路在代码注释中均有说明哦>_<.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
canvas {
display: block;
margin:10px auto;
border:2px solid #9FA8DA;
}
.option {
display: flex;
justify-content: space-around;
width: 500px;
height: 30px;
margin: auto;
}
#text {
text-align: center;
}
</style>
</head>
<body>
<canvas width="500px" height = "500px">
您的浏览器不支持canvas,请更换谷歌浏览器或升级您的浏览器
</canvas>
<div class="option">
<input type="color" id = 'colorList'>
<button id = "randomColor">随机颜色</button>
<button id="add">加粗</button>
<input type="text" id = "text" style = "width: 20px;" />
<button id="reduce">变细</button>
<button id="clear">清屏</button>
</div>
<script>
//获取canvas的DOM对象
let canvas = document.querySelector('canvas');
//获取上下文对象
let ctx = canvas.getContext('2d');
//定义初始的笔触样式
let strokeStyle = "#000";
let lineWidth = 6;
text.value = lineWidth;
//选择颜色
colorList.onchange = function () {
strokeStyle = this.value;
}
//产生随机颜色
randomColor.onclick = function() {
let arr = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F'];
let str = '#';
for (let i = 0; i < 6 ; i++) {
str += arr[Math.floor(Math.random()*16)];
}
strokeStyle = str;
// console.log(strokeStyle)
}
//加粗线条
add.onclick = function() {
if(lineWidth < 12) {
lineWidth += 2;
}
text.value = lineWidth;
}
//线条变细
reduce.onclick = function() {
if(lineWidth > 2) {
lineWidth -= 2;
}
text.value = lineWidth;
}
//鼠标按下事件
canvas.onmousedown = function(ev) {
ev = ev || window.event;
//更改颜色与笔触粗细
ctx.strokeStyle = strokeStyle;
ctx.lineWidth = lineWidth;
//开始绘图
ctx.beginPath();
ctx.moveTo(ev.offsetX,ev.offsetY);
//鼠标移动事件
canvas.onmousemove = function(ev) {
ctx.lineTo(ev.offsetX,ev.offsetY);
//绘制
ctx.stroke();
}
//鼠标抬起时取消移动和抬起事件绑定
document.onmouseup = function(ev) {
document.onmouseup = null;
canvas.onmousemove = null;
}
}
//清空屏幕
clear.onclick = function() {
ctx.clearRect(0 , 0 , 500 , 500);
}
</script>
</body>
</html>
最终的效果
需要注意的点是鼠标抬起事件要绑定给document,如果依旧绑定在canvas身上,会有bug出现,如下:
//鼠标按下事件
canvas.onmousedown = function(ev) {
ev = ev || window.event;
//更改颜色与笔触粗细
ctx.strokeStyle = strokeStyle;
ctx.lineWidth = lineWidth;
//开始绘图
ctx.beginPath();
ctx.moveTo(ev.offsetX,ev.offsetY);
//鼠标移动事件
canvas.onmousemove = function(ev) {
ctx.lineTo(ev.offsetX,ev.offsetY);
//绘制
ctx.stroke();
}
//鼠标抬起时取消移动和抬起事件绑定
canvas.onmouseup = function(ev) {
canvas.onmouseup = null;
canvas.onmousemove = null;
}
}
当我将鼠标慢速的移入移出canvas的区域时是正常的,但是如果我非常迅速的移动鼠标,鼠标移出之后迅速移入还可以继续画画,太快的移动根本反应不过来,如下图所示,因此我们应该将鼠标抬起事件绑定在document身上.