首页 文章

Konva stage.toDataUrl()是不是渲染我在画布中看到的图像?

提问于
浏览
0

我最近开始使用Konva库从Web API提供的数据在线创建一些图像 . 图像通常由一些文本,一些矩形和一些小图像组成 . 这些图像也来自同一个Web API . 我将它们转换为Base64字符串并将它们分配给img.src标记 . 所有这一切都很好,当它完成后,我看到一个画布,其中包含我期望看到的所有文本,作品和图像 .

当我尝试从舞台/画布创建PNG时会出现问题 . 画布渲染到图像,所有文本和线都在那里,但图像不是 . 起初我得到一个全黑的背景,但后来我发现以下文章提到需要渲染为PNG和/或制作不透明的背景 . 我之所以提到这一点,只是因为我想知道这里有类似的东西吗?

canvas.toDataURL results in solid black image?

无论如何,这里有一些代码片段,也许他们会帮助解决这个问题?

<div id="container"></div>

const stage = new Konva.Stage({
    container: 'container',
    width: width,
    height: height
});

const layer = new Konva.Layer();

switch...

    case 'Picture':
    {
        // Get the image from the Web API
        const image = this.store.images.getThumb(
            f.fldData.fldDataValue
        );

        const img = new Image();
        const t = this;

        // Create the Konva.Image() and add it to the stage
        img.onload = function() {
        // resize image keeping aspect ration
            response = t.calculateAspectRatioFit(img, w, h);
            const imgWidth = response.width;
            const imgHeight = response.height;

            const chPicture = new Konva.Image({
                x: x,
                y: y,
                image: img,
                width: imgWidth,
                height: imgHeight
            });

            // add the image to the layer
            layer.add(chPicture);

            // add the layer to the stage
            stage.add(layer);
        };

        image.subscribe(results => {
            // Convert image to Base64
            const fileReader = new FileReader();
            fileReader.readAsDataURL(results);
            // When it's ready, assign Base64 string to img src
            fileReader.onloadend = () => {
                img.src = fileReader.result;
            };
        });
    }
    break;

...

// Convert the image from the Web API to Base64
const dataURL = stage.toDataURL({
    mimeType: 'image/png',
    quality: 1.0
});

// Resize the image made from the canvas and display it on the screen
const container = document.getElementById('displayImage');
const i = new Image();
i.style.width = '320px';
i.style.height = '196px';
i.src = dataURL;
container.appendChild(i);

1 回答

  • 0

    img.onload 异步工作 . 这意味着稍后在加载图像时将执行回调函数 .

    正如我所看到的,在创建整个阶段后,您将同步保存到base64:

    // Convert the image from the Web API to Base64
    const dataURL = stage.toDataURL({
        mimeType: 'image/png',
        quality: 1.0
    });
    

    您只需要确保加载所有图像 . 然后才转换到dataURL .

相关问题