-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscratcher2.js
476 lines (399 loc) · 15.4 KB
/
scratcher2.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
/**
* Scratch-off canvas
*
* NOTE: this code monkeypatches Function.prototype.bind() if it doesn't
* already exist.
*
* NOTE: This is demo code that has been converted to be less demo-y.
* But it is still demo-y.
*
* To make (more) correct:
* o add error handling on image loads
* o fix inefficiencies
*
* depends on jQuery>=1.7
*
* Portions Copyright (c) 2012 Brian "Beej Jorgensen" Hall <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
Scratcher = (function() {
/**
* Helper function to extract the coordinates from an event, whether the
* event is a mouse or touch.
*/
function getEventCoords(ev) {
var first, coords = {};
var origEv = ev.originalEvent; // get from jQuery
if (origEv.changedTouches != undefined) {
first = origEv.changedTouches[0];
coords.pageX = first.pageX;
coords.pageY = first.pageY;
} else {
coords.pageX = ev.pageX;
coords.pageY = ev.pageY;
}
return coords;
};
/**
* Helper function to get the local coords of an event in an element.
*
* @param elem element in question
* @param ev the event
*/
function getLocalCoords(elem, coords) {
var offset = $(elem).offset();
return {
'x': coords.pageX - offset.left,
'y': coords.pageY - offset.top
};
};
/**
* Construct a new scratcher object
*
* @param canvasId [string] the canvas DOM ID, e.g. 'canvas2'
* @param backImage [string, optional] URL to background (bottom) image
* @param frontImage [string, optional] URL to foreground (top) image
*/
function Scratcher(canvasId, backImage, frontImage) {
this.canvas = {
'main': $('#' + canvasId).get(0),
'temp':null,
'draw':null
};
this.mouseDown = false;
this.canvasId = canvasId;
this._setupCanvases(); // finish setup from constructor now
this.setImages(backImage, frontImage);
this._eventListeners = {};
};
/**
* Set the images to use
*/
Scratcher.prototype.setImages = function(backImage, frontImage) {
this.image = {
'back': { 'url':backImage, 'img':null },
'front': { 'url':frontImage, 'img':null }
};
if (backImage && frontImage) {
this._loadImages(); // start image loading from constructor now
}
};
/**
* Returns how scratched the scratcher is
*
* By adjusting the stride, you get a less accurate result, but it is
* quicker to compute (pixels are skipped)
*
* @param stride [optional] pixel step value, default 1
*
* @return the fraction the canvas has been scratched (0.0 -> 1.0)
*/
Scratcher.prototype.fullAmount = function(stride) {
var i, l;
var can = this.canvas.draw;
var ctx = can.getContext("2d", { willReadFrequently: true });
var count, total;
var pixels, pdata;
if (!stride || stride < 1) { stride = 1; }
stride *= 4; // 4 elements per pixel
pixels = ctx.getImageData(0, 0, can.width, can.height);
pdata = pixels.data;
l = pdata.length; // 4 entries per pixel
total = (l / stride)|0;
for (i = count = 0; i < l; i += stride) {
if (pdata[i] != 0) {
count++;
}
}
return count / total;
};
/**
* Recomposites the canvases onto the screen
*
* Note that my preferred method (putting the background down, then the
* masked foreground) doesn't seem to work in FF with "source-out"
* compositing mode (it just leaves the destination canvas blank.) I
* like this method because mentally it makes sense to have the
* foreground drawn on top of the background.
*
* Instead, to get the same effect, we draw the whole foreground image,
* and then mask the background (with "source-atop", which FF seems
* happy with) and stamp that on top. The final result is the same, but
* it's a little bit weird since we're stamping the background on the
* foreground.
*
* OPTIMIZATION: This naively redraws the entire canvas, which involves
* four full-size image blits. An optimization would be to track the
* dirty rectangle in scratchLine(), and only redraw that portion (i.e.
* in each drawImage() call, pass the dirty rectangle as well--check out
* the drawImage() documentation for details.) This would scale to
* arbitrary-sized images, whereas in its current form, it will dog out
* if the images are large.
*/
Scratcher.prototype.recompositeCanvases = function() {
var tempctx = this.canvas.temp.getContext('2d');
var mainctx = this.canvas.main.getContext('2d');
// Step 1: clear the temp
this.canvas.temp.width = this.canvas.temp.width; // resizing clears
tempctx.save();
tempctx.beginPath();
tempctx.arc(50, 50, 50, 0, Math.PI * 2, true);
tempctx.closePath();
tempctx.clip();
// Step 2: stamp the draw on the temp (source-over)
tempctx.drawImage(this.canvas.draw, 0, 0);
tempctx.beginPath();
tempctx.arc(0, 0, 50, 0, Math.PI * 2, true);
tempctx.clip();
tempctx.closePath();
tempctx.restore();
// Step 3: stamp the background on the temp (!! source-atop mode !!)
tempctx.globalCompositeOperation = 'source-atop';
tempctx.drawImage(this.image.back.img, 0, 0,this.image.back.img.width, this.image.back.img.height,0,0,this.canvas.temp.width,this.canvas.temp.height);
mainctx.save();
mainctx.beginPath();
mainctx.arc(50, 50, 50, 0, Math.PI * 2, true);
mainctx.closePath();
mainctx.clip();
// Step 4: stamp the foreground on the display canvas (source-over)
mainctx.drawImage(this.image.front.img, 0, 0,this.image.front.img.width, this.image.front.img.height,0,0,this.canvas.temp.width,this.canvas.temp.height);
mainctx.beginPath();
mainctx.arc(0, 0, 50, 0, Math.PI * 2, true);
mainctx.clip();
mainctx.closePath();
mainctx.restore();
// Step 5: stamp the temp on the display canvas (source-over)
mainctx.drawImage(this.canvas.temp, 0, 0);
};
/**
* Draw a scratch line
*
* Dispatches the 'scratch' event.
*
* @param x,y the coordinates
* @param fresh start a new line if true
*/
Scratcher.prototype.scratchLine = function(x, y, fresh) {
var can = this.canvas.draw;
var ctx = can.getContext('2d');
can.getContext("2d", { willReadFrequently: true });
ctx.lineWidth = 10;
ctx.lineCap = ctx.lineJoin = 'round';
ctx.strokeStyle = '#f00'; // can be any opaque color
if (fresh) {
ctx.beginPath();
// this +0.01 hackishly causes Linux Chrome to draw a
// "zero"-length line (a single point), otherwise it doesn't
// draw when the mouse is clicked but not moved:
ctx.moveTo(x+0.01, y);
}
ctx.lineTo(x, y);
ctx.stroke();
// call back if we have it
this.dispatchEvent(this.createEvent('scratch'));
};
/**
* Set up the main canvas and listeners
*/
Scratcher.prototype._setupCanvases = function() {
var c = this.canvas.main;
// create the temp and draw canvases, and set their dimensions
// to the same as the main canvas:
this.canvas.temp = document.createElement('canvas');
this.canvas.draw = document.createElement('canvas');
this.canvas.temp.width = this.canvas.draw.width = c.width;
this.canvas.temp.height = this.canvas.draw.height = c.height;
/**
* On mouse down, draw a line starting fresh
*
* Dispatches the 'scratchesbegan' event.
*/
function mousedown_handler(e) {
var local = getLocalCoords(c, getEventCoords(e));
this.mouseDown = true;
this.scratchLine(local.x, local.y, true);
this.recompositeCanvases();
this.dispatchEvent(this.createEvent('scratchesbegan'));
return false;
};
/**
* On mouse move, if mouse down, draw a line
*
* We do this on the window to smoothly handle mousing outside
* the canvas
*/
function mousemove_handler(e) {
if (!this.mouseDown) { return true; }
var local = getLocalCoords(c, getEventCoords(e));
this.scratchLine(local.x, local.y, false);
this.recompositeCanvases();
return false;
};
/**
* On mouseup. (Listens on window to catch out-of-canvas events.)
*
* Dispatches the 'scratchesended' event.
*/
function mouseup_handler(e) {
if (this.mouseDown) {
this.mouseDown = false;
this.dispatchEvent(this.createEvent('scratchesended'));
return false;
}
return true;
};
$(c).on('mousedown', mousedown_handler.bind(this))
.on('touchstart', mousedown_handler.bind(this));
$(document).on('mousemove', mousemove_handler.bind(this));
$(document).on('touchmove', mousemove_handler.bind(this));
$(document).on('mouseup', mouseup_handler.bind(this));
$(document).on('touchend', mouseup_handler.bind(this));
};
/**
* Reset the scratcher
*
* Dispatches the 'reset' event.
*
*/
Scratcher.prototype.reset = function() {
// clear the draw canvas
this.canvas.draw.width = this.canvas.draw.width;
this.recompositeCanvases();
// call back if we have it
this.dispatchEvent(this.createEvent('reset'));
};
/**
* returns the main canvas jQuery object for this scratcher
*/
Scratcher.prototype.mainCanvas = function() {
return this.canvas.main;
};
/**
* Handle loading of needed image resources
*
* Dispatches the 'imagesloaded' event
*/
Scratcher.prototype._loadImages = function() {
var loadCount = 0;
// callback for when the images get loaded
function imageLoaded(e) {
loadCount++;
if (loadCount >= 2) {
// call the callback with this Scratcher as an argument:
this.dispatchEvent(this.createEvent('imagesloaded'));
this.reset();
}
}
// load BG and FG images
for (k in this.image) if (this.image.hasOwnProperty(k)) {
this.image[k].img = document.createElement('img'); // image is global
$(this.image[k].img).on('load', imageLoaded.bind(this));
this.image[k].img.src = this.image[k].url;
}
};
/**
* Create an event
*
* Note: not at all a real DOM event
*/
Scratcher.prototype.createEvent = function(type) {
var ev = {
'type': type,
'target': this,
'currentTarget': this
};
return ev;
};
/**
* Add an event listener
*/
Scratcher.prototype.addEventListener = function(type, handler) {
var el = this._eventListeners;
type = type.toLowerCase();
if (!el.hasOwnProperty(type)) {
el[type] = [];
}
if (el[type].indexOf(handler) == -1) {
el[type].push(handler);
}
};
/**
* Remove an event listener
*/
Scratcher.prototype.removeEventListener = function(type, handler) {
var el = this._eventListeners;
var i;
type = type.toLowerCase();
if (!el.hasOwnProperty(type)) { return; }
if (handler) {
if ((i = el[type].indexOf(handler)) != -1) {
el[type].splice(i, 1);
}
} else {
el[type] = [];
}
};
/**
* Dispatch an event
*/
Scratcher.prototype.dispatchEvent = function(ev) {
var el = this._eventListeners;
var i, len;
var type = ev.type.toLowerCase();
if (!el.hasOwnProperty(type)) { return; }
len = el[type].length;
for(i = 0; i < len; i++) {
el[type][i].call(this, ev);
}
};
/**
* Set up a bind if you don't have one
*
* Notably, Mobile Safari and the Android web browser are missing it.
* IE8 doesn't have it, but <canvas> doesn't work there, anyway.
*
* From MDN:
*
* https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind#Compatibility
*/
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal
// IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP
? this
: oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
return Scratcher;
})();