-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcanvasPenJS_usingMDNCodeSamples.js
209 lines (206 loc) · 7.9 KB
/
canvasPenJS_usingMDNCodeSamples.js
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
/*canvasPenJS_usingMDNCodeSamples.js
* ======
* some code samples for "Toutch events" were derived on 2017-01-16
* and from "Touch events" by 2005-2017 Mozilla Developer Network (MDN)
* and individual contributors.
* ======
* Copyright (c) 2016 Yuji SODE <yuji.sode@gmail.com>
*
* This software is released under the MIT License.
* See LICENSE or http://opensource.org/licenses/mit-license.php
*/
//this is interface for drawing on target canvas tag.
/* === parameters ===
* canvas: target canvas tag
* rgba: color
* w: line width
* plot: true|false; true => plotting, false => drawing
* >- plot can be a text: a pair of values with @.
* >- this pair of values are expressed as "x@y" e.g., "1@2", "10.5@100.31".
* === returned value ===
* function that removes the set drawing/plotting interface
* and returns log object: {time:string,d:[],canvasId:id of canvas}.
*/
function _canvasPenJS(canvas,rgba,w,plot){
//============================================================================
var slf=window,cvs=slf.document.getElementById(canvas.id),I=0,n=0,c,x=0,y=0,Rect,
log={time:0,d:[],canvasId:canvas.id},
/*a pair of values are expressed as "x@y" e.g., "1@2,10.5@100.31".*/
reg=/^(?:\+|\-)?[0-9]+(?:\.[0-9]+)?@(?:\+|\-)?[0-9]+(?:\.[0-9]+)?$/,
plotFlg,
evnt=[
['mousedown','mouseup','mousemove','mouseout'],
['mouseup'],
['touchstart','touchmove','touchend']
];
plotFlg=reg.test(plot);
//relative position of the canvas to the viewport
Rect=!!cvs.getBoundingClientRect()?cvs.getBoundingClientRect():{top:0,left:0};
/* --- Reference ---
* -"MDN: Element.getBoundingClientRect()" derived on 2016-12-28 and from:
* https://developer.mozilla.org/en/docs/Web/API/Element/getBoundingClientRect
*/
//============================================================================
//== <Handling clicks with touch event: code samples from MDN> ==
/* these code samples were derived on 2017-01-16 and from:
* "Additional tips/Handling clicks" in "Touch events"
* by 2005-2017 Mozilla Developer Network (MDN) and individual contributors:
* https://developer.mozilla.org/en/docs/Web/API/Touch_events
* the contributors to "Touch events":
* chrisdavidmills, andrew-luhring, Luke314, teoli, cassidoo, mrenty, AFBarstow,
* Sebastianz, ammist, TotalAMD, mnquintana, mkato, Sheppy, rschmidmeister, Changbin,
* maynarddemmon, Dotcom, Thomas-Brierley, jdawson, Jeremie, kscarfone, timothykim,
* kohei.yoshino, Gawi, Darbicus, robstar, avih, complynx, Brainversation, ethertank,
* foolip, Nickolay, MykMelez, GrapWhit3, openjck,arleytriana, freejosh, smeranda,
* julienw, oncletom, wesj, yahelc, MattBrubeck, jswisher
* ------
* Any copyright of These code samples from MDN is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/
* ------
*/
function onTouch(evt) {
evt.preventDefault();
if (evt.touches.length > 1 || (evt.type == "touchend" && evt.touches.length > 0))
return;
var newEvt = document.createEvent("MouseEvents");
var type = null;
var touch = null;
switch (evt.type) {
case "touchstart":
type = "mousedown";
touch = evt.changedTouches[0];
break;
case "touchmove":
type = "mousemove";
touch = evt.changedTouches[0];
break;
case "touchend":
type = "mouseup";
touch = evt.changedTouches[0];
break;
}
newEvt.initMouseEvent(type, true, true, evt.originalTarget.ownerDocument.defaultView, 0,
touch.screenX, touch.screenY, touch.clientX, touch.clientY,
evt.ctrlKey, evt.altKey, evt.shiftKey, evt.metaKey, 0, null);
evt.originalTarget.dispatchEvent(newEvt);
}
//== </Handling clicks with touch event: code samples from MDN> ==
if(!plot){
//=== drawing ===
var dr=function(e){
//e: event, dr.d[0]=flag:true|false, dr.d[1]=x0, dr.d[2]=y0
if(!dr.d){dr.d=[false,0,0];}
var D=dr.d;
/*Event: mousedown*/
if(!(e.type!='mousedown')){
D[0]=true,D[1]=e.clientX-Rect.left,D[2]=e.clientY-Rect.top;
//log.d is an array of plots, expressed with x and y coordinates: "x@y".
log.d.push(D[1]+'@'+D[2]);
}
/*Event: mouseup*/
else if(!(e.type!='mouseup')){
D[0]=false,x=e.clientX-Rect.left,y=e.clientY-Rect.top;
//log.d is an array of plots, expressed with x and y coordinates: "x@y".
log.d.push(x+'@'+y);
}
/*Event: mousemove|mouseout*/
else if(!(e.type!='mousemove')||!(e.type!='mouseout')){
if(D[0]){
x=e.clientX-Rect.left,y=e.clientY-Rect.top;
c=cvs.getContext('2d'),c.strokeStyle=rgba,c.lineWidth=w;
c.beginPath(),c.moveTo(D[1],D[2]),c.lineTo(x,y),c.stroke();
D[1]=x,D[2]=y;
//reset strokeStyle and lineWidth
c.strokeStyle='rgba(0,0,0,1)',c.lineWidth=1;
if(!(e.type!='mouseout')){
D[0]=false;
//log.d is an array of plots, expressed with x and y coordinates: "x@y".
log.d.push(x+'@'+y);
}
}
}
};
}else if(!!plotFlg){
//=== plotting ===
//plotting with data: x@y
var pltData=function(){
//plot: a pair of values are expressed as "x@y" e.g., "1@2", "10.5@100.31".
c=cvs.getContext('2d'),c.strokeStyle=rgba,c.lineWidth=w;
x=+plot.split(/@/)[0],y=+plot.split(/@/)[1];
c.strokeRect(x,y,1,1);
//log.d is an array of plots, expressed with x and y coordinates: "x@y".
log.d.push(plot);
//reset strokeStyle and lineWidth
c.strokeStyle='rgba(0,0,0,1)',c.lineWidth=1;
};
}else{
//plotting
var plt=function(e){
//e: event
c=cvs.getContext('2d'),c.strokeStyle=rgba,c.lineWidth=w;
x=e.clientX-Rect.left,y=e.clientY-Rect.top;
c.strokeRect(x,y,1,1);
//log.d is an array of plots, expressed with x and y coordinates: "x@y".
log.d.push(x+'@'+y);
//reset strokeStyle and lineWidth
c.strokeStyle='rgba(0,0,0,1)',c.lineWidth=1;
};
}
//============================================================================
//Handling clicks with touch event
cvs=slf.document.getElementById(canvas.id),n=evnt[2].length,I=0;
while(I<n){cvs.addEventListener(evnt[2][I],onTouch,true),I+=1;}
if(!plot){
//=== drawing ===
n=evnt[0].length,I=0;
log.d=[],log.time='drawing:'+slf.Date().replace(/\s/g,'_')+' to ';
while(I<n){cvs.addEventListener(evnt[0][I],dr,true),I+=1;}
//returned function
return function(){
cvs=slf.document.getElementById(canvas.id),I=0;
log.time+=slf.Date().replace(/\s/g,'_');
while(I<n){cvs.removeEventListener(evnt[0][I],dr,true),I+=1;}
//reset strokeStyle and lineWidth
if(!c){c=cvs.getContext('2d');}
c.strokeStyle='rgba(0,0,0,1)',c.lineWidth=1;
//it returns log object.
return log;
};
}else if(!!plotFlg){
//=== plotting ===
//plotting with data: x@y
log.d=[],log.time='plotting with data (x@y):'+slf.Date().replace(/\s/g,'_');
pltData();
//returned function
return function(){
//reset strokeStyle and lineWidth
if(!c){c=cvs.getContext('2d');}
c.strokeStyle='rgba(0,0,0,1)',c.lineWidth=1;
//it returns log object.
return log;
};
}else{
//plotting
log.d=[],log.time='plotting:'+slf.Date().replace(/\s/g,'_')+' to ';
cvs.addEventListener(evnt[1][0],plt,true);
//returned function
return function(){
cvs=slf.document.getElementById(canvas.id);
log.time+=slf.Date().replace(/\s/g,'_');
cvs.removeEventListener(evnt[1][0],plt,true);
//reset strokeStyle and lineWidth
if(!c){c=cvs.getContext('2d');}
c.strokeStyle='rgba(0,0,0,1)',c.lineWidth=1;
//it returns log object.
return log;
};
}
}
//=== examples ===
//var d=window.document.getElementsByTagName('canvas')[0];
//var Y=_canvasPenJS(d,'rgba(255,0,0,1)',2,false);
//Y();
//var Y=_canvasPenJS(d,'rgba(0,0,255,1)',10,true);
//Y();
//var Y=_canvasPenJS(d,'rgba(255,0,255,1)',10,"20@+13.14");
//Y();