简体   繁体   中英

How do I insert my image data from array into canvas so that I can download it?

I'm making a web app for drawing pixel art. The app itself works, I can choose canvas size, colors and tools to draw. Now I want to generate an image from it. My canvas is a grid of divs that change background color when you draw on them. I made a function that creates a 2D array with each item having 4 values (red, green, blue, alpha). Here's a function I use:

function rgb2pngStart(val) {
    let finish = val.length - 1;
    let sliced = val.slice(4, finish)
    let stringAr = sliced.split(', ');
    let R = parseInt(stringAr[0]);
    let G = parseInt(stringAr[1]);
    let B = parseInt(stringAr[2]);
    let pixelArray = [R, G, B, 255];
    return pixelArray;
}

function createArray() {
    let sideInPixels = document.documentElement.style.getPropertyValue('--number');
    let canvasX = [];
    let canvasY = [];
    for (let i = 1; i <= sideInPixels; i++) {
        for (let j = 1; j <= sideInPixels; j++) {
            let pixel = document.getElementById(i + ' ' + j).style.backgroundColor;
            canvasX[j - 1] = rgb2pngStart(pixel);
        }
        canvasY[i - 1] = canvasX;
    }
    return canvasY; 
}

I was trying to create a canvas, using some old answers here, and put my data into imagedata and then show that image to user so that he could download it. But I don't know how do I do that...

So, how do I generate image from this array? Or what should I change for it to work?

The most convenient approach would be to use an actual <canvas> element: you can create ImageData from your RGBA pixel information and put it to the canvas context — and then generate a data URL or a blob , which can be used to create an object URL (both of which can be used as download targets).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM