LingDong- / q5xjs

A small and fast alternative (experimental) implementation of p5.js
https://q5xjs.netlify.app/
The Unlicense
544 stars 25 forks source link

Q5.Image() has problems with a Source Rectangle #16

Closed ybx97 closed 2 years ago

ybx97 commented 2 years ago

Hey Ling,

Absolutely amazing project this is. I've been using Q5 in my own project because it's incredible. When creating a loading bar I ran into a strange issue that seemed related to Q5. Q5.Image() does not (properly) handle the source parameters in the way that P5 does.

The package configuration of my project contains Q5XJS ^0.0.5 and P5 ^1.4.0. I've reproduced this issue with the latest version of this repo too.

The image should load in from left to right. When using this code on Q5XJS it seems to stretch the image instead. I've provided code that you can run within the P5 Web Editor.

let img;
let start = Date.now(); 

function setup() {
  createCanvas(400, 400);
  img = loadImage('https://i.imgur.com/FjTgVcE.jpeg');
}

function draw() {
  background(220);

  let progress = (Date.now() - start) / 1000.0 % 1;

  let loadingbarPosition = {
     x: 0,
     y: 0 
  };

  let loadingbarSize = {
     width: 128,
     height: 128
  }

 if(img) image(   
    img, 
    loadingbarPosition.x, 
    loadingbarPosition.y,
    loadingbarSize.width  * progress, 
    loadingbarSize.height,
    0, // sx
    0, // sy
    img.width * progress, // sw
    img.height // sh
  );
}
ybx97 commented 2 years ago

This issue is due to an (unintended?) (bug?) of Javascript comparisons.

if (!sx){ returns true when 'sx' == 0.

The solution is to simply replace if(!sx) with if(sx == undefined).