简体   繁体   中英

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

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)
    }

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