査辰昊IP属地: 江西
2018.12.13 15:24:56字数 224阅读 2,775
本期的小需求:
在页面中实现一个能进行绘画的画板
能实现画笔颜色、粗细、撤回等功能
开发环境
Vue + elementUI
采坑记录
- 画笔与鼠标错位 (恶心很久)
- 画笔切换颜色 粗细,原来绘画的线条也改变了
- 图片跨域等等…
动手
1.生成或选中canvas对象
1 <canvas id="box"></canvas>
2
3let canvas = $("#canvas")[0]
2.生成绘画画布环境
1let canvas = $("#canvas")[0]
2
3let ctx = canvas.getContext("2d")
ps: canvas 画板绘制api
1 ctx.fillRect(x, y, width, height)
2
3ctx.strokeRect(x, y, width, height)
4
5ctx.clearRect(x, y, widh, height)
6
7ctx.beginPath()
8
9ctx.moveTo(x, y)
10
11ctx.closePath()
12
13ctx.stroke()
14
15ctx.fill()
16
17ctx.arc(x, y, r, startAngle, endAngle, anticlockwise):
18
19ctx.arcTo(x1, y1, x2, y2, radius):
3.canvas 画板实现
实现思路: 监听鼠标事件,用drawCircle()方法画出来
- 监听画板区域鼠标事件,未开始时设置painting 为 false
- 当鼠标按下时(mousedown),开启画笔函数,painting为true,鼠标松开之前记录路径点,并绘制记录点
- 使用lineTo()函数把每个点连接
- 鼠标松开的时候(mouseup),关闭画笔函数
1data(){
2 return{
3 isClear:false
4 }
5}
6canvasLoad(){
7 let canvas = $("box")[0];
8 let context = canvas.getContext("2d");
9
10 let img = new Image();
11 img.src = "";
12
13 img.onload = () =>{
14
15 let width = img.width
16 let height = img.height
17
18 canvas.width = width
19 canvas.height = height
20
21
22
23
24 context.drawImage(img, 0, 0, width,height);
25
26 this.drawLine()
27
28 $("#blackBtn").click(() => {
29 context.strokeStyle = "#000000";
30 });
31 $("#whiteBtn").click(() => {
32 context.strokeStyle = "#FFFFFF";
33 });
34 $("#clearBtn").click(() => {
35
36 context.clearRect(0,0,innerWidth,innerHeight)
37 });
38 $("#eraserBtn").click(() => {
39
40 this.isClear=true;
41 });
42 $("#widthBtn").click(() => {
43
44
45 context.lineWidth = width;
46 });
47
48
49
50 }
51}
52drawLine() {
53 const that = this
54 let canvas = $("#box")[0];
55 let context = canvas.getContext("2d");
56 context.canvas.addEventListener("mousedown", startAction)
57
58 context.canvas.addEventListener("mouseup", endAction)
59
60 function startAction(event) {
61
62
63 if (!that.isClear) {
64
65 context.beginPath();
66 context.lineCap = "round";
67
68 context.moveTo(event.pageX,event.pageY);
69 context.stroke();
70 }
71 context.canvas.addEventListener("mousemove", moveAction);
72 }
73
74 function endAction() {
75
76 that.isClear=false;
77
78 context.canvas.removeEventListener("mousemove",moveAction);
79 }
80 function moveAction(event) {
81
82 if(that.isClear){
83 context.clearRect(event.pageX-8,event.pageY-8,16,16);
84 return;
85 }
86 context.lineTo(event.pageX,event.pageY);
87 context.stroke();
88 }
89}
4.实现撤回功能
1data(){
2 return{
3 ...
4 canvasHistory
5 }
6}
7....
8canvasLoad(){
9 ...
10 $("#recallBtn").click(() => {
11
12 img.src = that.canvasHistory[that.canvasHistory.length-1]
13
14
15 this.canvasLoad()
16
17 that.canvasHistory.pop()
18 });
19
20 ...
21
22}
23drawLine(){
24 function startAction() {
25 ...
26 that.canvasHistory.push(canvas.toDataURL())
27
28 }
29}
个人笔记记录 2021 ~ 2025