简体   繁体   中英

How do I add a scrollbar to a rectangle in an HTML5 canvas?

Is there a standard way to add a scrollbar to a rectangle in an HTML5 canvas? I would like to add a vertical scrollbar to a rectangle that contains a list of items that is longer than the canvas. Is there a library that does this sort of thing? Or, is this something I will have to figure out for myself.

There is no standard way unfortunately. Canvas is just representing a bitmap (image). There are only pixels and everything drawn outside is clipped.

To add scrollbar you have to create one yourself. A trick is also to put the canvas inside a div and use the scrollbar of the div but this is not recommended as it consumes far more memory.

Scrollbars are not so hard to create though; look at some existing code to see how they are made and try to adopt them for use on canvas. You find some easily by google them, here is one example (you could perhaps use that as-is too).

The basic steps are:

➔ Calculate the total arbitrary size of the complete page (lets stick to height for now)
➔ Calculate the ratio between the actual height of canvas and the arbitrary height
➔ Calculate the height as viewport relative to the total height

The latter is used to draw the knob inside the scrollbar container. When you move the knob each pixel represent a certain size of the arbitrary height which you calculated in the second step.

That's the basis - there are some other things such as when the arbtrary height is less the actual height so scrollbar is hidden or knob fills the whole space, you have to subtract the height of the knob in the calculation so you can move it to the bottom and it will represent the bottom of the arbitrary height.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM