p5.js: 绘图工具在移动设备上运行不佳

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

对于一个项目,我想使用这个代码:

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>

我意识到它在移动设备上运行不佳。有时什么都没有画,有时我会得到一些彩色点。应该可以用手指“正常”画画。

有办法解决吗?非常感谢您的帮助! <3

这不能作为 Whosebug 上的可运​​行代码段使用,因为它们不会显示在移动设备上,但你可以 (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;
    }
}

有关详细信息,请参阅 p5.js 参考的 Events - Touch 部分。