I am creating a game using JavaScript an HTML canvas on my webpage. I want to make the experience as smooth as possible, so I want to try and prevent any user actions, eg. scrolling, zooming, selection. I also want it to work across different browsers.
My experience with trying to fix this is that HTML <meta>
tags haven’t really helped and JavaScript solutions have most been pretty clunky, which is not really the solution I’m after.
Here is some CSS code that I have tried to use. Some of it works but there are still lots of issues with scrolling, zooming etc. and lots of other edge cases.
body, html, #canvas {
width: 100%;
height: 100%;
pointer-events: none;
touch-action: none;
zoom: none;
-webkit-zoom-in: none;
-webkit-zoom-out: none;
scroll: none;
scrollbar: none;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
-webkit-user-select: none;
user-select: none;
}
Is there any way to just disable all user interactions and then start again from scratch?
2
Answers
Ok so here is a few tricky ways to do it, depending on what device are you targeting.
If you wanna target the mobile device the head meta viewport should work.
As described in this Stack overflow question How can I "disable" zoom on a mobile web page?.
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
But if you wanna target all devices like PC, Mobile and so on…. You will need to list all the events in javascript and do preventDefault on those events.
I would strongly recommend using some library for games (as mention in the original post comment) Phaser is a good one. Or if you wanna go the hard way you can always grab three.js library and go all out.
I hope this one helped you a little bit.
To disable all user interactions such as scrolling, zooming, and selection, you can use the combined approach of CSS and JavaScript. It will help achieve this across different browsers.
Explanation:
overflow: hidden
onhtml
andbody
to prevent scrolling.touch-action: none
.user-select: none
.touchmove
), keydown events for specific keys (like arrow keys and spacebar), and the right-click context menu.