konvajs / konva

Konva.js is an HTML5 Canvas JavaScript framework that extends the 2d context by enabling canvas interactivity for desktop and mobile applications.
http://konvajs.org/
Other
11.07k stars 896 forks source link

Problem with Loading Video (Konva.Node.create) #1748

Closed XShaan closed 2 months ago

XShaan commented 2 months ago

I am currently working on developing a layout system for creating both text and video content. Currently, I do not encounter any issues when saving the data using stage.toJSON() to the database. However, I am facing a problem with loading it on another page.

The text displays without any issues, but I'm encountering difficulties with displaying the video content. Although no errors are appearing in the console, the video is not being shown consistently. Occasionally, after 20-30 refreshes, it will appear once.

Could anyone assist me in identifying the problem in my code?

load data on another page :

<script>
  const canvasData = @json($this->layout->objects);
  loadFromJSON(canvasData);
</script>

konva.js :

function addVideo(url) {
    var video = document.createElement('video');
    video.src = url;
    video.autoplay = true;
    video.loop = true;

    var videoNode = new Konva.Image({
        x: 10,
        y: 10,
        stroke: 'black', // border color
        strokeWidth: 2, // border thickness
        draggable: true,
        videoUrl: url // Add custom attribute to store video URL
    });

    video.onloadedmetadata = function() {
        videoNode.image(video);
        videoNode.width(video.videoWidth);
        videoNode.height(video.videoHeight);
        layer.add(videoNode);
        layer.draw();
    };

    function updateFrame() {
        layer.draw();
        requestAnimationFrame(updateFrame);
    }

    video.onplay = function() {
        updateFrame();
    };
}

export function loadFromJSON(json) {
    if (json) {
        var stage = Konva.Node.create(json, 'myCanvas');
        stage.children.forEach(layer => {
            layer.find('Image').forEach(function(imageNode) {
                addVideo(imageNode.getAttr('videoUrl'));
            });
        });
    }
}

Result :

4-16-2024 (21-46-22)

lavrton commented 2 months ago

Hello. I see that after loading a JSON you are adding NEW Konva.Image into the canvas with video source. I think it is better to reuse existing instance.

Please create a small demo of your issue.