简体   繁体   中英

HTML5 canvas and scrolling

I have a canvas element of size 1024x768 where I draw a very large image, let's just say with width >> 1024 and height >> 768. The image can be scrolled with normal scrollbars to be seen entirely.

Users can click onto the canvas to add vertices to a polygon: each time a vertex is added, a line from the new vertex to the mouse cursor is drawn. Each mouse movement onto the canvas updates the canvas in order to redraw such line from the vertex to the new mouse cursor position.

Being the image VERY large, redrawing is very slow, so I'd like to just redraw the currently visible chunk of image or, even better, the "sub-chunk" that is affected by this line.

The problem is: how do I detect the current topLeft and bottomRight of the visible part of the context according to how much the user scrolled the image? Basically I'd like to add support for a custom viewport, but I can't seem to exploit the scolling information to determine the boundingBox of the chunk to crop from the original image.

I actually have a canvasDiv container, which is the real scrollable element, not the canvas itself.

This means your canvas is the full size and you're using the container div as a sort of a "frame". That's really bad as canvas pixels are quite expensive, especially if you're not even using them (they're out of the viewport).

The best approach here is to set the canvas size to the container size and use the drawImage function to control the scrolling. The original image would be places either on an offscreen canvas or an image element. I can guarantee you a much better performance this way.

You'll lose the scrollbars, that's the downside.

I'm assuming you create the scrollbars by having a larger canvas element contained inside a smaller div.

Instead, you can mimic this setup by:

  • Having a canvas the size of your container div.

  • Add 2 input type=range controls to act as vertical & horizontal scrollbars (or grab a jqueryUI scrollbar plugin if you want to be fancy).

  • Then you can use the clipping version of context.drawImage to draw only the portion of the image specified by the range controls. The clipping version of drawImage looks like this: drawImage(myLargeImage, clipX,clipY,clipWidth,clipHeight, 0,0,canvas.width,canvas.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