Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Canvas render image fail (?) #2389

Open
qaqFei opened this issue Jun 7, 2024 · 0 comments
Open

Canvas render image fail (?) #2389

qaqFei opened this issue Jun 7, 2024 · 0 comments

Comments

@qaqFei
Copy link

qaqFei commented Jun 7, 2024

For examples(you should has "./test.png" file and "./images" folder):

const canvas = require('canvas');
const fs = require('fs');

async function main(){
    cv = canvas.createCanvas(500, 500);
    ctx = cv.getContext('2d');
    img = await canvas.loadImage('./test.png');
    width = 250;
    height = 250;
    cut = 0;
    for (;;) {
        width --;
        height --;
        cut ++;
        if (width < -5 || height < -5) {
            width = 250;
            height = 250;
        }
        ctx.clearRect(0, 0, 500, 500);
        ctx.drawImage(img, 0, 0, width, height);
        buf = cv.toBuffer('image/png');
        fs.writeFileSync(`./images/${cut}.png`, buf);
        console.log(width, height, cut);
    }
}

main();

if the width < 0 or height < 0, canvas.toBuffer will return null value(isnot "null").

how to fix?

add this code:

canvas.CanvasRenderingContext2D.prototype._drawImage = canvas.CanvasRenderingContext2D.prototype.drawImage
canvas.CanvasRenderingContext2D.prototype.drawImage = function(im, x, y, w, h){ //not perfect
    if (w < 0 || h < 0) return;
    this._drawImage(im, x, y, w, h);
}

but this is not perfect, because this function has other usage.

(I am a Chinese, so my English is not good.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant