使用canvas制作绘图板
模仿了windows绘图板,用canvas做了一个绘图板,可以调整线条颜色,粗细,清除画布等功能
先看看实际效果图
以下为代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas</title>
<style type="text/css">
#canvas {
border: 1px solid black;
}
#choose{
width: 300px;
}
</style>
</head>
<body>
<div id="choose">
<input type="color" id="color">
<select name="" id="lineWidth">
<option value="5">--请选择线条粗细(像素)--</option>
<option value="2">2px</option>
<option value="5">5px</option>
<option value="8">8px</option>
<option value="12">12px</option>
<option value="15">15px</option>
</select>
<input type="button" id="btnClear" value="清除画布">
</div>
<canvas id="canvas" width="500" height="500"></canvas>
</body>
<script type="text/javascript">
//获取画布
let canvas = document.getElementById("canvas"); //获取canvas元素
let context = canvas.getContext("2d"); //获取绘图上下文context
//获取其他元素
let color = document.getElementById("color");
let lineWidth = document.getElementById("lineWidth");
let btn = document.getElementById("btnClear");
//判断是否开始绘图
let isDraw = false;
//绘图
//鼠标摁下时开始绘图
canvas.onmousedown = function (){
isDraw = true;
//颜色
context.strokeStyle = color.value;
//线宽
context.lineWidth = lineWidth.value;
//开始绘制
context.beginPath();
//指定绘制起点
context.moveTo(event.offsetX,event.offsetY);
}
//鼠标移动进行绘图
canvas.onmousemove = function (){
if(isDraw){
//指定绘制终点
context.lineTo(event.offsetX,event.offsetY);
//描边
context.stroke();
}
}
//鼠标松开停止绘图
canvas.onmouseup = function (){
isDraw = false;
}
//当鼠标移出画布时,停止绘图
canvas.onmouseout = function(){
isDraw = false;
}
//清除画布
btn.onclick = function(){
context.clearRect(0,0,canvas.width,canvas.height);
}
</script>
</html>
注:canvas的宽高直接在canvas标签中写即可,不要在css中去指定宽高!