For a project, I would like to work with this code:
JavaScript
x
19
19
1
let colors;
2
let color;
3
4
function setup() {
5
let c = createCanvas(windowWidth, windowHeight);
6
colors = [[155, 204, 250], [205, 104, 200], [255, 0, 0], [0, 255, 0], [0, 0, 255]];
7
color = random(colors);
8
}
9
10
function mouseClicked() {
11
color = random(colors);
12
}
13
14
function mouseMoved() {
15
stroke(color);
16
strokeWeight(20);
17
line(mouseX, mouseY, pmouseX, pmouseY);
18
return false;
19
}
JavaScript
1
1
1
<script src="https://cdn.jsdelivr.net/npm/p5@1.4.0/lib/p5.js"></script>
I realized that it doesn’t work well on mobile devices. Sometimes nothing draws, sometimes I get some colored dots. It should possible to draw “normally” with the finger.
Is there a way to fix that? Would be very thankful for help! <3
Advertisement
Answer
This won’t work as a runnable snippet on StackOverflow because they don’t show up on mobile devices, but here you go (runnable version on OpenProcessing):
JavaScript
1
62
62
1
let colors;
2
let color;
3
4
function setup() {
5
createCanvas(windowWidth, windowHeight);
6
colors = [
7
[155, 204, 250],
8
[205, 104, 200],
9
[255, 0, 0],
10
[0, 255, 0],
11
[0, 0, 255]
12
];
13
color = random(colors);
14
}
15
16
function isTouchDevice() {
17
return (('ontouchstart' in window) ||
18
(navigator.maxTouchPoints > 0) ||
19
(navigator.msMaxTouchPoints > 0));
20
}
21
22
if (isTouchDevice()) {
23
let previousTouches;
24
touchStarted = function(e) {
25
// Note: when touching multiple times this will reset the color for all of the lines.
26
color = random(colors);
27
28
previousTouches = [touches];
29
}
30
31
touchMoved = function(e) {
32
if (previousTouches) {
33
for (let i = 0; i < touches.length && i < previousTouches.length; i++) {
34
let prev = previousTouches[i];
35
let touch = touches[i];
36
stroke(color);
37
strokeWeight(20);
38
line(prev.x, prev.y, touch.x, touch.y);
39
}
40
previousTouches = [touches];
41
}
42
// Prevent zooming and scrolling gestures
43
e.preventDefault();
44
return false;
45
}
46
47
touchEnded = function(e) {
48
previousTouches = [touches];
49
}
50
} else {
51
mousePressed = function() {
52
color = random(colors);
53
}
54
55
mouseDragged = function() {
56
stroke(color);
57
strokeWeight(20);
58
line(mouseX, mouseY, pmouseX, pmouseY);
59
return false;
60
}
61
}
62
For more info see the Events – Touch section fo the p5.js reference.