How to correctly convert images and attach to canvas in p5js?

Currently I’m working on a big project where I’m drawing the shoe model in canvas and using some functions to divide them into segments. Those segments are clickable in order to change the images depending on which and how many colors have been chosen. So, let say if we have selected 3 colors then my helper function will generate new image from those colors (or basically will change the colors of current image into new colors).

It works fine, but currently I have 6 segments in total and it does not really work good, so it is not really 100% reliable.

First, I would like to share some variables I have:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>// some variables to initialize
let initializeDrawingsCalled = false;
let segmentToInitialize = null;
let initializationDelayCounter = 0;
const INITIALIZATION_DELAY_FRAMES = 4;
// related to images and segments
let img = {
tongue: null,
// some other values
};
let segmentTextureMask = {
tongue: null,
// some other values
}
let createMask = {
tongue: null,
// some other values
}
var initVariables = {
// selected parts
selectedSegment: null,
// to get the loading for specific segment
loading: {
TONGUE: false,
// some other values
},
};
</code>
<code>// some variables to initialize let initializeDrawingsCalled = false; let segmentToInitialize = null; let initializationDelayCounter = 0; const INITIALIZATION_DELAY_FRAMES = 4; // related to images and segments let img = { tongue: null, // some other values }; let segmentTextureMask = { tongue: null, // some other values } let createMask = { tongue: null, // some other values } var initVariables = { // selected parts selectedSegment: null, // to get the loading for specific segment loading: { TONGUE: false, // some other values }, }; </code>
// some variables to initialize
let initializeDrawingsCalled = false;
let segmentToInitialize = null;
let initializationDelayCounter = 0;
const INITIALIZATION_DELAY_FRAMES = 4;

// related to images and segments
let img = {
    tongue: null,
    // some other values
};

let segmentTextureMask = {
    tongue: null,
    // some other values
}

let createMask = {
    tongue: null,
    // some other values
}

var initVariables = {
    // selected parts
    selectedSegment: null,
    // to get the loading for specific segment
    loading: {
        TONGUE: false,
        // some other values
    },
};

and my sketch function is like following:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>export const shoeSketch = (p5Instance) => {
p5 = p5Instance;
// initially just loading simple white image
p5.preload = () => {
const baseUrl = '/img/white.png';
img.collarSide = p5.loadImage(baseUrl);
img.collarFront = p5.loadImage(baseUrl);
img.heelSide = p5.loadImage(baseUrl);
img.sidePanel = p5.loadImage(baseUrl);
img.sideCap = p5.loadImage(baseUrl);
img.tongue = p5.loadImage(baseUrl);
}
p5.setup = () => {
// these two functions are used to load the shoe model, nothing fancy
createMeasurementSet();
createCps();
p5.createCanvas(1300, 500, p5.WEBGL);
};
}
p5.draw = () => {
p5.background(initVariables.lightGrey);
// this updateCPs take some time to finalize putting points correctly in canvas
updateCPs();
// thus I need to have counter like this to initialize drawings
if (!initializeDrawingsCalled) {
initializationDelayCounter++;
if (initializationDelayCounter > INITIALIZATION_DELAY_FRAMES) {
initializeDrawings();
initializeDrawingsCalled = true;
}
}
</code>
<code>export const shoeSketch = (p5Instance) => { p5 = p5Instance; // initially just loading simple white image p5.preload = () => { const baseUrl = '/img/white.png'; img.collarSide = p5.loadImage(baseUrl); img.collarFront = p5.loadImage(baseUrl); img.heelSide = p5.loadImage(baseUrl); img.sidePanel = p5.loadImage(baseUrl); img.sideCap = p5.loadImage(baseUrl); img.tongue = p5.loadImage(baseUrl); } p5.setup = () => { // these two functions are used to load the shoe model, nothing fancy createMeasurementSet(); createCps(); p5.createCanvas(1300, 500, p5.WEBGL); }; } p5.draw = () => { p5.background(initVariables.lightGrey); // this updateCPs take some time to finalize putting points correctly in canvas updateCPs(); // thus I need to have counter like this to initialize drawings if (!initializeDrawingsCalled) { initializationDelayCounter++; if (initializationDelayCounter > INITIALIZATION_DELAY_FRAMES) { initializeDrawings(); initializeDrawingsCalled = true; } } </code>
export const shoeSketch = (p5Instance) => {
    p5 = p5Instance;
    // initially just loading simple white image
    p5.preload = () => {
        const baseUrl = '/img/white.png';
        img.collarSide = p5.loadImage(baseUrl);
        img.collarFront = p5.loadImage(baseUrl);
        img.heelSide = p5.loadImage(baseUrl);
        img.sidePanel = p5.loadImage(baseUrl);
        img.sideCap = p5.loadImage(baseUrl);
        img.tongue = p5.loadImage(baseUrl);
    }

   p5.setup = () => {
        // these two functions are used to load the shoe model, nothing fancy
        createMeasurementSet();
        createCps();

        p5.createCanvas(1300, 500, p5.WEBGL);
    };
}

    p5.draw = () => {
        p5.background(initVariables.lightGrey);
        // this updateCPs take some time to finalize putting points correctly in canvas
        updateCPs(); 

        // thus I need to have counter like this to initialize drawings
        if (!initializeDrawingsCalled) {
            initializationDelayCounter++;
            if (initializationDelayCounter > INITIALIZATION_DELAY_FRAMES) {
                initializeDrawings();
                initializeDrawingsCalled = true;
            }
        }

and two helper functions to initializeDrawings and drawImages are used to initialize the masks in the canvas and draw images using p5.image() function.

Most importantly, I have changeSegmentImage where it changes the segment image, but first it gets imageUrl to convert image to file, and then using replaceColors I convert the image colors into new colors passed and create uri from it and attach it to mask using loadImage.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>export const changeSegmentImage = async (imageUrl, colors) => {
try {
// Validate imageUrl
if (!imageUrl) throw new Error("Invalid image URL");
initVariables.loading[initVariables.selectedSegment] = true;
// Convert imageUrl to file
const file = await imageUrlToFile(imageUrl);
// Replace colors in the file
const converted_file = await replaceColors(file, colors);
// Create a URL for the converted file
const uri = URL.createObjectURL(converted_file); // it is correct, image generated is fine
// Load the image based on the selected segment
// problem appears to be here with loadImage function
switch (initVariables.selectedSegment) {
case 'COLLARSIDE':
img.collarSide = p5.loadImage(uri);
break;
// and others
default:
throw new Error("Invalid segment selected");
}
// Reset initialization flags
initializeDrawingsCalled = false;
segmentToInitialize = initVariables.selectedSegment;
} catch (error) {
console.error("Error changing collar side image:", error);
} finally {
// Ensure loading state is set to false
initVariables.loading[initVariables.selectedSegment] = false;
}
};
</code>
<code>export const changeSegmentImage = async (imageUrl, colors) => { try { // Validate imageUrl if (!imageUrl) throw new Error("Invalid image URL"); initVariables.loading[initVariables.selectedSegment] = true; // Convert imageUrl to file const file = await imageUrlToFile(imageUrl); // Replace colors in the file const converted_file = await replaceColors(file, colors); // Create a URL for the converted file const uri = URL.createObjectURL(converted_file); // it is correct, image generated is fine // Load the image based on the selected segment // problem appears to be here with loadImage function switch (initVariables.selectedSegment) { case 'COLLARSIDE': img.collarSide = p5.loadImage(uri); break; // and others default: throw new Error("Invalid segment selected"); } // Reset initialization flags initializeDrawingsCalled = false; segmentToInitialize = initVariables.selectedSegment; } catch (error) { console.error("Error changing collar side image:", error); } finally { // Ensure loading state is set to false initVariables.loading[initVariables.selectedSegment] = false; } }; </code>
export const changeSegmentImage = async (imageUrl, colors) => {
    try {
        // Validate imageUrl
        if (!imageUrl) throw new Error("Invalid image URL");
        initVariables.loading[initVariables.selectedSegment] = true;

        // Convert imageUrl to file
        const file = await imageUrlToFile(imageUrl);

        // Replace colors in the file
        const converted_file = await replaceColors(file, colors);

        // Create a URL for the converted file
        const uri = URL.createObjectURL(converted_file); // it is correct, image generated is fine

        // Load the image based on the selected segment
        // problem appears to be here with loadImage function
        switch (initVariables.selectedSegment) {
            case 'COLLARSIDE':
                img.collarSide = p5.loadImage(uri);
                break;
            // and others
            default:
                throw new Error("Invalid segment selected");
        }

        // Reset initialization flags
        initializeDrawingsCalled = false;
        segmentToInitialize = initVariables.selectedSegment;

    } catch (error) {
        console.error("Error changing collar side image:", error);
    } finally {
        // Ensure loading state is set to false
        initVariables.loading[initVariables.selectedSegment] = false;
    }
};

It works all good if I have only two segments visible, but if I have more segments (like 5-6) then it gets slower and actually does not load the image using loadImage.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật