本文实例为大家分享了js+canvas实现画板功能的具体代码,供大家参考,具体内容如下
1.实现了画图,改变画笔粗细,改变画笔颜色,清屏功能
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<!DOCTYPE html>
< html >
< head >
< meta charset = "utf-8" />
< title >画板</ title >
< link rel = "shortcut icon" type = "image/x-icon" href = "img/an.ico" />
< link rel = "stylesheet" type = "text/css" href = "css/drow.css" />
</ head >
< body >
< canvas id = "mycanvas" width = "1100px" height = "660px" ></ canvas >
< div class = "tool" >
画笔颜色:< input type = "color" name = "color1" id = "color1" />< br />
画笔粗细:< input type = "range" name = "range1" id = "range1" min = "1" max = "20" />< br />
< button class = "btn" >清屏</ button >
</ div >
</ body >
< script src = "js/drow.js" type = "text/javascript" charset = "utf-8" ></ script >
</ html >
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
*{
margin : 0 ;
padding : 0 ;
text-align : left ;
-moz-user-select: none ;
-ms-user-select: none ;
-webkit-user-select: none ;
}
#mycanvas{
border : 2px solid deepskyblue;
}
.tool{
width : 260px ;
height : 100% ;
position : fixed ;
right : 0 ;
top : 0 ;
background-color : #CCCCCC ;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
//获取对象
var mycanvas = document.getElementById( "mycanvas" );
var color1 = document.getElementById( "color1" );
var range1 = document.getElementById( "range1" );
var btn = document.getElementsByClassName( "btn" )[0];
var contxt = mycanvas.getContext( "2d" );
btn.onclick= function () {
contxt.clearRect(0,0,1200,660);
}
var flag = false ;
var x = 0,
y = 0;
// 鼠标点下事件
mycanvas.onmousedown = function (event) {
flag = true ;
// 获取鼠标点下的开始位置
var x = event.clientX - mycanvas.offsetLeft;
var y = event.clientY - mycanvas.offsetTop;
contxt.beginPath(); // 开始新建路径
contxt.strokeStyle = color1.value; // 获得颜色赋值给画笔
contxt.lineCap= "round" ;
contxt.lineWidth = range1.value; // 获得画笔宽度赋值给画笔
contxt.moveTo(x, y); // 开始位置
}
// 鼠标移动事件
mycanvas.onmousemove = function (event) {
// 获取鼠标在移动的位置
var mX = event.clientX - mycanvas.offsetLeft;
var mY = event.clientY - mycanvas.offsetTop;
if (flag) {
contxt.lineTo(mX, mY); // 移动途中和结束位置
contxt.stroke(); // 结束渲染画布
}
}
// 鼠标松开事件
mycanvas.onmouseup = function () {
flag = false ;
}
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/m0_46690660/article/details/108475674