P5.js - createGraphics() 导致屏幕尺寸小的奇怪结果

P5.js - createGraphics() leads to strange results with small screen size

几天来我一直在努力解决这个问题。我用这个简单的代码简化了问题:

let graphicCanvas
let ctx
let speed = 1
function setup(){
    cnv = createCanvas(windowWidth, windowHeight)
    cnv.style('display', 'block');
    graphicCanvas = createGraphics(800,800)
    ctx = graphicCanvas.canvas.getContext('2d')
    
}
function draw(){
    ctx.drawImage(ctx.canvas,0,0,800,800,0,speed,800,800)

    graphicCanvas.noStroke()
    graphicCanvas.fill(255,0,0)
    graphicCanvas.circle(100,100,50)
    image(graphicCanvas,0,0)
    
}

这段代码应该显示一个红色圆圈的轨迹,它在每次循环后变长: Red trails

问题在于此代码仅适用于大屏幕。对于小屏幕,我最终得到了这个结果:Red circles

我不知道问题出在 createGraphics()drawImage() 还是 image()

我已经尝试使用 graphicCanvas.push() 和 graphicCanvas.pop() 但没有任何改变。如何获得每种屏幕尺寸的“红色轨迹”结果?

(作为老外,英文错误请见谅)

问题不在于屏幕尺寸,而在于像素密度。因为您使用的是 CanvasRenderingContext2D.drawImage 函数而不是 p5.js 函数,所以图形在绘制时实际上缩放了 2 倍。这是一个适用于任何屏幕的示例:

let graphicCanvas;
let ctx;
let speed = 1;

function setup() {
  pixelDensity(1);
  cnv = createCanvas(windowWidth, windowHeight);
  cnv.style("display", "block");
  graphicCanvas = createGraphics(800, 800);
  ctx = graphicCanvas.canvas.getContext("2d");
}

function draw() {
  ctx.drawImage(ctx.canvas, 0, 0, 800, 800, 0, speed, 800, 800);

  graphicCanvas.noStroke();
  graphicCanvas.fill(255, 0, 0);
  graphicCanvas.circle(100, 100, 50);
  image(graphicCanvas, 0, 0);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>

那是说您可能要考虑完全避免原生 CanvasRenderingContext2D 函数并使用 p5.js 保留对像素密度支持的函数:

let graphicCanvas;
let ctx;
let speed = 1;
function setup() {
  cnv = createCanvas(windowWidth, windowHeight);
  speed = pixelDensity();
  cnv.style("display", "block");
  graphicCanvas = createGraphics(800, 800);
}
function draw() {
  graphicCanvas.copy(0, 0, 800, 800, 0, speed, 800, 800);

  graphicCanvas.noStroke();
  graphicCanvas.fill(255, 0, 0);
  graphicCanvas.circle(100, 100, 50);
  image(graphicCanvas, 0, 0);
}