Chrome中的Canvas drawImage

问题描述 投票:0回答:1

我需要更改背景颜色以匹配Wordpress行中的视频颜色。它适用于firefox \ edge \ safari但在chrome中不起作用。它返回RGB(0,0,0)

有问题的页面 - http://flex.tmweb.ru

window.onload = function() {
    var vid = document.getElementById('video-15-1_html5');
    var row = document.getElementById('globe-video');
    var canvas = document.createElement('canvas');

    canvas.width = 1;
    canvas.height = 1;

    var context = canvas.getContext('2d');
    context.drawImage(vid, 0, 0, 1, 1);

    var p = context.getImageData(0, 0, 1, 1).data;
    row.style.backgroundColor = "rgb(" + p[0] + "," + p[1] + "," + p[2] + ")";
};
javascript wordpress html5 canvas
1个回答
0
投票

我的猜测是存在某种时间问题,Chrome在调用onload时与在视频本身加载任何内容时有所不同。

在做画布之前尝试检查视频是否已加载,然后在必要时等待:

function onVideoLoaded() {
    var vid = document.getElementById('video-15-1_html5');
    var row = document.getElementById('globe-video');
    var canvas = document.createElement('canvas');

    canvas.width = 1;
    canvas.height = 1;

    var context = canvas.getContext('2d');
    context.drawImage(vid, 0, 0, 1, 1);

    var p = context.getImageData(0, 0, 1, 1).data;
    row.style.backgroundColor = "rgb(" + p[0] + "," + p[1] + "," + p[2] + ")";
}

window.onload = function() {
    var vid = document.getElementById('video-15-1_html5');

    if (vid.readyState === 4) {
        onVideoLoaded();
    } else {
        vid.addEventListener('loadeddata', function () {
            if (vid.readyState === 4) {
                onVideoLoaded();
            }
        });
    }
};

请参阅HTMLMediaElement.readyState上的此MDN文档:https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/readyState

© www.soinside.com 2019 - 2024. All rights reserved.