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
|
window.addEventListener('load', function(evt) {
let paintStyle = getComputedStyle(document.querySelector('section'));
let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');
canvas.width = parseInt(paintStyle.getPropertyValue('width'));
canvas.height = parseInt(paintStyle.getPropertyValue('height'));
var mouse = {
x: 0,
y: 0
};
ctx.lineWidth = 3;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = 'limegreen';
canvas.addEventListener('mousemove', function(e) {
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
}, false);
canvas.addEventListener('mousedown', function(e) {
ctx.beginPath();
ctx.moveTo(mouse.x, mouse.y);
canvas.addEventListener('mousemove', onPaint, false);
}, false);
canvas.addEventListener('mouseup', function() {
canvas.removeEventListener('mousemove', onPaint, false);
}, false);
var onPaint = function() {
ctx.lineCap = 'round';
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
};
document.querySelectorAll('nav button').forEach(function(button, idx) {
button.addEventListener('click', function(evt) {
console.log(button.dataset.method);
switch (button.dataset.method) {
case 'color':
{
ctx.strokeStyle = button.dataset.value;
break;
}
case 'size':
{
ctx.lineWidth = parseInt(button.dataset.value);
break;
}
case 'clear':
{
let clear = confirm('Do you really want to clear canvas?');
if (clear) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
break;
}
}
});
});
});
|