Konva stage.toDataUrl()无法呈现在画布中看到的图像?

时间:2018-07-20 23:19:08

标签: canvas konvajs

我最近开始使用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 :(得分:0)

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

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

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

您只需要确保已加载所有图像。然后才转换为dataURL。