画布:检测在浏览器中是否可见 [英] Canvas: Detect if it is visible in browser

查看:68
本文介绍了画布:检测在浏览器中是否可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图表列表.我使用 Chart.js 来创建这些图表.因为我的列表可以包含1到100个或更多条目,所以一次初始化所有图表并不明智,因为这会使ui长时间冻结.因此,相反,我认为只初始化那些在浏览器视图范围内可见的图表会更好,例如,只有第一个图表被初始化,并且当用户向下滚动而第二个画布变为可见时,第二个是进行初始化等等.

I have a list of charts. I use Chart.js to create those charts. Since my list can have 1 to 100 or more entries initializing all charts at once would not be smart because that would make the ui freeze for a long time. So instead I thought it would be much better to only initialize those charts which are visible inside the view bounds of the browser so that for example only the first chart is getting initialized and when the user scrolls down and the second canvas becomes visible the second is getting initialized and so on.

我已完成所有设置,但现在唯一的问题是:如何创建事件监听器或类似的东西,可以将其添加到在画布在浏览器的视图范围内可见时触发的每个画布元素中这样我就可以为该画布执行图表初始化了?

I have everything setup but the only problem that I have right now is: how can I create an eventlistener or anything similiar which I can add to each canvas element that gets triggered when a canvas becomes visible inside the view bounds of the browser so that i can perform the chart initialization for that canvas?

推荐答案

我是OnScreen的作者,它是一个小型库,可以在HTMLElement进入视口或其容器的边界时调用回调函数./p>

I'm the author of OnScreen, a small library that can call a callback function when a HTMLElement enters the viewport or the boundaries of its container.

// Uses ES6 syntax
import OnScreen from 'onscreen';

const os = new OnScreen();

os.on('enter', 'canvas', (element) => {
    if (!element.chartInitialized) {
        // Initialize the chart

        // Update the `chartInitialized` property
        // to avoid initializing it over and over
        element.chartInitialized = true;
    }
});

有关更多信息,请查看文档 .不要忘记查看 demos存储库中的几个简单示例.

For more information, take a look at the documentation. Don't forget to check the demos repo for a couple simple examples.

这篇关于画布:检测在浏览器中是否可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆