Skip to content
Advertisement

p5.js: Drawing tool doesn’t work well on mobile devices

For a project, I would like to work with this code:

let colors;
let color;

function setup() {
  let c = createCanvas(windowWidth, windowHeight);
  colors = [[155, 204, 250], [205, 104, 200], [255, 0, 0], [0, 255, 0], [0, 0, 255]];
  color = random(colors);
}

function mouseClicked() {
  color = random(colors);
}

function mouseMoved() {
  stroke(...color);
  strokeWeight(20);
  line(mouseX, mouseY, pmouseX, pmouseY);
  return false;
}
<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):

let colors;
let color;

function setup() {
    createCanvas(windowWidth, windowHeight);
    colors = [
        [155, 204, 250],
        [205, 104, 200],
        [255, 0, 0],
        [0, 255, 0],
        [0, 0, 255]
    ];
    color = random(colors);
}

function isTouchDevice() {
    return (('ontouchstart' in window) ||
        (navigator.maxTouchPoints > 0) ||
        (navigator.msMaxTouchPoints > 0));
}

if (isTouchDevice()) {
    let previousTouches;
    touchStarted = function(e) {
        // Note: when touching multiple times this will reset the color for all of the lines.
        color = random(colors);

        previousTouches = [...touches];
    }

    touchMoved = function(e) {
        if (previousTouches) {
            for (let i = 0; i < touches.length && i < previousTouches.length; i++) {
                let prev = previousTouches[i];
                let touch = touches[i];
                stroke(...color);
                strokeWeight(20);
                line(prev.x, prev.y, touch.x, touch.y);
            }
            previousTouches = [...touches];
        }
        // Prevent zooming and scrolling gestures
        e.preventDefault();
        return false;
    }

    touchEnded = function(e) {
        previousTouches = [...touches];
    }
} else {
    mousePressed = function() {
        color = random(colors);
    }

    mouseDragged = function() {
        stroke(...color);
        strokeWeight(20);
        line(mouseX, mouseY, pmouseX, pmouseY);
        return false;
    }
}

For more info see the Events – Touch section fo the p5.js reference.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement