Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in using canvas.toDataURL() in react- native with npm react-native-canvas latest

    const image = new CanvasImage(canvas);
    canvas.width = 100;
    canvas.height = 100;
    const context = canvas.getContext('2d');
    image.src = 'http://i.imgur.com/c2wRzfD.jpg';
    image.addEventListener('load', async () => {
        context.drawImage(image, 0, 0, 100, 100);
        let dataURL = await canvas.toDataURL("image/png")
    });

This code gives me error like:

"Cannot read property 'constructor' of undefined"

This comes only when I drawImage() on canvas it works properly when I draw rectangle, round etc.

Android Studio is 3.0.1

node -v is stabble

like image 845
preshita soni Avatar asked Feb 02 '26 00:02

preshita soni


1 Answers

The problem is with this cod inside the listener

let dataURL = await canvas.toDataURL("image/png")

It seems to break your constructor definition to the drawImage

This can be solved by using it as follows

 handleImageRect = async (canvas) => {
        const image = new CanvasImage(canvas);
        canvas.width = 100;
        canvas.height = 100;

        const context = canvas.getContext('2d');

        image.src = 'https://image.freepik.com/free-vector/unicorn-background-design_1324-79.jpg';
        image.addEventListener('load', () => {
            console.log('image is loaded');
            context.drawImage(image, 0, 0, 100, 100);

        });
        // Move it outside
        let dataURL =  await canvas.toDataURL("image/png")
        console.log(dataURL)
    }
like image 188
Pritish Vaidya Avatar answered Feb 03 '26 13:02

Pritish Vaidya