-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscratch-off-reveal-with-HTML5-Canvas.html
80 lines (70 loc) · 2.21 KB
/
scratch-off-reveal-with-HTML5-Canvas.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Scratch Off Reveal With HTML5 Canvas</title>
<link rel="stylesheet" href="css/scratch-off-reveal-with-HTML5-Canvas.css">
</head>
<body>
<figure id="bridgeContainer">
<canvas id="bridge" width="750" height="465"></canvas>
<figcaption>Downtown Calgary in 2013 and 1943; mouse down or touch on photo to reveal</figcaption>
</figure>
</body>
<script>
var bridge = document.getElementById('bridge'),
bridgeCanvas = bridge.getContext('2d'),
brushRadius = (bridge.width / 100) * 5,
img = new Image();
if (brushRadius < 50) { brushRadius = 50}
img.onload = function () {
bridgeCanvas.drawImage(img, 0, 0, bridge.width, bridge.height);
}
img.loc = 'images/';
img.filename = 'calgary-bridge-2013.jpg';
if (window.devicePixelRatio >= 2) {
var nameParts = img.filename.split('.');
img.src = img.loc + nameParts[0]+ "-2x" + "."+ nameParts[1];
}
else {
img.src = img.loc + img.filename;
}
function detectLeftButton (event) {
if ('buttons' in event) {
return event.buttons === 1;
} else if ('which' in event) {
return event.which === 1;
} else {
return event.button === 1;
}
}
function getBrushPos (xRef, yRef) {
var bridgeRect = bridge.getBoundingClientRect();
return {
x: Math.floor((xRef - bridgeRect.left) / (bridgeRect.right - bridgeRect.left) * bridgeRect.width),
y: Math.floor((yRef - bridgeRect.top) / (bridgeRect.bottom - bridgeRect.top) * bridgeRect.height)
};
}
function drawDot (mouseX, mouseY) {
bridgeCanvas.beginPath();
bridgeCanvas.arc(mouseX, mouseY, brushRadius, 0, 2*Math.PI, true);
bridgeCanvas.fillStyle = '#000';
bridgeCanvas.globalCompositeOperation = 'destination-out';
bridgeCanvas.fill();
}
bridge.addEventListener('mousemove', function (e) {
var brushPos = getBrushPos(e.clientX, e.clientY);
var leftBut = detectLeftButton(e);
if (leftBut == 1) { drawDot(brushPos.x, brushPos.y)}
}, false);
bridge.addEventListener('touchmove', function (e) {
e.preventDefault();
var touch = e.targetTouches[0];
if (touch) {
var brushPos = getBrushPos(touch.pageX, touch.pageY);
drawDot(brushPos.x, brushPos.y);
}
}, false);
</script>
</html>