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

Time:02-08

I've been trying to solve this problem for days. I simplified the problem with this simple code :

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)
    
}

This code is supposed to show the trails,of a red circle, that is getting longer after each loop: Red trails

The problem is that this code only works on large screens. With small screens I end up with this result : Red circles

I don't know if the problem comes from the createGraphics(), the drawImage() or the image().

I already tried to use graphicCanvas.push() and graphicCanvas.pop() but nothing change. How can I get the "Red trails" result for every screen size ?

(As a foreigner, please excuse me for the english mistakes)

CodePudding user response:

The issue is not screen size, but pixel density. Because you are using the CanvasRenderingContext2D.drawImage function instead of p5.js function the graphics is actually scaled 2x when it is drawn. Here's an example that should work on any screen:

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>

That said you might want to consider avoiding the native CanvasRenderingContext2D functions altogether and use p5.js functions that preserve support for pixel density:

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);
}
  •  Tags:  
  • Related