I was wondering how I could go about making a camera-like view where I could scroll a level within a canvas element just like this:
2D side scrolling camera view in html5
23k Views Asked by Oni Enzeru At
2
There are 2 best solutions below
4
hobberwickey
On
I've always found it's more efficient to wrap your canvas in a div with the width and height of your viewport and the overflow set to hidden then just draw your whole canvas and scroll the div to where you where you want to view.
So the html would be:
<div id='wrapper' style='width: 200px; height: 200px; overflow: hidden;'>
<canvas width='1000' height='1000'></canvas>
</div>
and the javascript would be something like
function scrollWrapper(x, y){
var wrapper = document.getElementById('wrapper');
wrapper.scrollTop = x;
wrapper.scrollLeft = y;
}
Then just call the function with the x and y you want to view. you could wrap it in a setTimeout or something if you wanted to move there instead of just jumping there.
Related Questions in JAVASCRIPT
- Using Puppeteer to scrape a public API only when the data changes
- inline SVG text (js)
- An array of images and a for loop display the buttons. How to assign each button to open its own block by name?
- Storing the preferred font-size in localStorage
- Simple movie API request not showing up in the console log
- Authenticate Flask rest API
- Deploying sveltekit app with gunjs on vercel throws cannot find module './lib/text-encoding'
- How to request administrator rights?
- mp4 embedded videos within github pages website not loading
- Scrimba tutorial was working, suddenly stopped even trying the default
- In Datatables, start value resets to 0, when column sorting
- How do I link two models in mongoose?
- parameter values only being sent to certain columns in google sheet?
- Run main several times of wasm in browser
- Variable inside a Variable, not updating
Related Questions in HTML
- How to store a date/time in sqlite (or something similar to a date)
- How to use custom font during html to pdf conversion?
- Storing the preferred font-size in localStorage
- mp4 embedded videos within github pages website not loading
- Scrimba tutorial was working, suddenly stopped even trying the default
- Is there any way to glow this bulb image like a real light bulb
- With non-graphical maps in Leaflet, zoomDelta doesn't work
- What can I do to improve my coding on both html and css
- Uncaught TypeError: google.maps.LatLng is not a constructor at init (script.js:7:13)
- Bootstrap modal not showing at the desired position on a web page when the screen size is smaller
- Displaying a Movie List on a Website Using Jinja2 and Bootstrap
- How to redirect to thank you page after submitting a Google form embedded into a Google Site?
- Storing selected language in localStorage
- Fences (parenthesis, braces) in HTML and MathML
- Understanding Scroll Anchoring Behavoir
Related Questions in CANVAS
- Random number generator in Python Canvas
- When I use electron js and canvas in node js, I get a rebuild module error
- How to set an individual mouse scroll on two different canvases that are connected to separate frames but the frames are one on top of eachother?
- Positioning for sliders and canvas
- How to perfectly align textarea and canvas fillText
- Rust Ownership Challenges in Drawing Application: Need Assistance with Code Section
- Zoom In/Out particular Object with Touch in Fabric JS
- How to send a big array to a client faster
- Android: How to scale a bitmap to fit the screen size using canvas?
- How can i resize canva and send resized data to database?
- Given a convex polygon as a set of edges how to fill the area inside depending on the distance to the closest edge
- SigmaJS: Create a snapshot of "sigma-containter"
- Draw local image on canvas using react-native-canvas
- Rotating multiple objects around the origin (JavaScript Canvas)
- How to proper rotate object with a 45-degree angle using OrbitControls?
Related Questions in CAMERA
- Trained ML model with the camera module is not giving predictions
- godot lean mechanic makes camera glitch
- Can not switch camera while recording with camera plugin, setDescription working but preview doesn't change
- How to Python Open CV Web Cam 4EA Real time Streaming
- Problem picking up with interactive camera and orbitcontrols after amination camera moves "camera view"
- I can't find a conenction diagarm for the OV7670 camera to the ESP8266
- Camera rotation to direction vector
- What does "Simultaneous Live View Up to 6 channels" imply for a IP Camera specification
- RTSP camera sub stream url
- Android record video from multiple cameras and composite the multiple videos into one video
- Orienting a camera that orbits spheres in JOGL2
- Unity render Texture is not as clear as the actual gameobject in the scene, how to make it clearer?
- AR motion design exhibition in the real space of the city
- What is the correct approach to always use the latest camera frame in OpenCV
- OnVif authentication failed for Milesight camera
Related Questions in SIDE-SCROLLER
- How to scroll inner page of Facebook Meta Ads library?
- How can I create an angle in which an object must follow in pygame?
- C# script for moving platforms in a 2D Unity game, code is not making the correct menu for an array in the inspector
- Unity 2d side scoller character jump no matter the speed
- How can I set the same value to vars but run them seperately in different functions?
- How to go about enabling side scrolling in Wagtail admin site
- Unity3d - Rigidbody vs CharacterController vs transform.Translate for Sidescroller
- If an elements style.left reaches something, change style.left to something else
- How to display or move sprite in as3 side scroller?
- Procedural generated 2D caves/dungeons for sidescroller like game
- Adjusting the ship's speed and limiting the ship's range Python Pygame
- Automatically scrolling to my player using p5.js, but it does not work
- Disabling side-scrolling works on desktop but not mobile
- how to show html and css select scroller bar for both vertical and horizontal
- Scrolling background in Processing with Fisica/Box2D
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Popular # Hahtags
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?

So you want a 500x500 canvas to display something (a game level) that is really 9000x500 or so.
This is fine. What you do is think of the canvas as a "viewport" for a larger scene. You translate the canvas (or everything else) to the appropriate spot and draw all of the relevant things at that spot.
Here's an example:
http://jsfiddle.net/hKrrY/
Click on the canvas and hold down your left arrow key to see the scene go by while the red player dot stays "still".
As you scroll by the 100x100 canvas, you are seeing objects that are being drawn at once-offscreen locations like (330,50). Translating the canvas brings them into view.
I guess its worth mentioning that this is where making optimizations in a canvas starts to really matter. The example I gave above is a very simplistic way to make a viewport, and as your code progresses you're going to want to think more and more about what it is you're drawing and how much you're drawing. You'll want to avoid drawing objects that are completely offscreen, for instance, and if your game or app has a background that is 9000x500 you probably don't want to be drawing the entire thing every time!
So the concept is the takeaway here, but you'll want to think very hard about how you implement it and how much work you are making the canvas do. If you end up with performance problems in your side-scrolling app, be sure to let us know :)