Creating objects with adjustable X and Y positions based on HTML Canvas dimensions

I'm in the process of developing a basic game that utilizes HTML5 Canvas technology.

Within the canvas, I've incorporated multiple rectangles to enhance gameplay.

However, one issue I've encountered is related to how I control the rectangles using X and Y coordinates. While the game performs well on my current display, it presents a problem on smaller screens where objects can stray beyond the designated "map" area. Conversely, on larger displays, more of the map becomes visible.

How can I make this game responsive to different screen sizes?

Below is an excerpt of the code I'm using to initialize the canvas:

    this.canvas.width = document.body.clientWidth - 15;
    this.canvas.height = 700;
    this.context = this.canvas.getContext("2d");

Additionally, here's a snippet illustrating how the rectangles are moved within the game loop:

    cursor.x += 1;

Answer №1

Ensure that the dimensions of the canvas are set to a size that does not exceed the screen size in both width and height.

Afterwards, whenever you move the rectangle, include a condition to check if it remains within the visible area.

For example:

if (cursor.x + 1 < this.canvas.width) {
  cursor.x += 1;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to show a message when I hover over a different text?

I've been attempting to show a text when hovering over another text, but for some reason it's not working. I've followed all the steps from similar questions, but unfortunately, it still doesn't seem to be functioning correctly. Here i ...

Reserved space for both double and single quotation marks

I've created a function that generates a table of specified size with predetermined content in each cell, and displays it within a designated div ID. generate_table(4, 4, 'Cell Content', 'display') To test this function, I added a ...

Exploring the world of flexbox and experimenting with implementing flex-wrap at a specific breakpoint

I am working on a layout that includes a module containing various content. My goal is to have the progress bar, along with the labels "parts" and "projects," positioned underneath an image and expand to the full width of the module when the window size go ...

Vue.js - Duplicate Navigation Error When Redirected to a New Page

I'm facing an issue with Vue.js and the NavigationDuplicated error. As I work on a web application that involves navigation across various pages, I encounter the "NavigationDuplicated" error unexpectedly. Even though I'm not attempting to naviga ...

The Node.js microservice encountered a timeout when attempting to connect with another microservice

My issue involves hosting microservices on an ec2 instance. The services work perfectly in the development environment, but encounter a problem when running on the production environment using HTTPS. One of the services is unable to connect to another serv ...

Can you guide me on implementing first-person controls in react-three-fiber?

I'm attempting to set up a scenario where the camera remains stationary while allowing users to rotate the view around either the y or x axis by dragging their mouse. I'm looking for something akin to the functionality seen on threejs.org/example ...

Encountered a parsing issue while attempting to retrieve JSON data from an API in Dialogflow

I am currently working on retrieving JSON data from the iex API. Utilizing Google's Dialogflow inline editor, I encountered an error while attempting to fetch the JSON information: Error: Parse Error at Error (native) at Socket.socketOnData (_http_cl ...

React does not allow objects as children, but what if it's actually an array?

My function is encountering an error message that reads: "Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead." I am struggling to understand why this error is occurring. ...

There seems to be an issue with the syntax in ReactJS: the URL is

I'm facing an issue in my React code. I have a function that doesn't seem to be in the correct format for React. check(img) { console.log(img,typeof img) const url=""; const arrN = ["15","16","35","36","37","38","39","40" ...

Implementing flash messages with a delay in an express 4 application

I am currently using Passport.js with a local strategy to authenticate users on my web application. However, I have noticed a delay in setting the flash message. I have tried using the {message: ''} option in Passport and manually setting the fla ...

Pattern matching for censoring various elements within a string

I'm utilizing regular expressions in JavaScript to redact certain information. The regex below successfully replaces part of the values. EDIT Original String: mysql --user=USER_NAME --host=DB_HOST --database=SCHEMA -p -e 'SELECT Expression: ...

The file that is currently being downloaded has the .pptx extension, but it is being

Take a look at this code snippet: const generateDownload = ({ link, data, title, settings })=> { const newLink = document.createElement('a'); const blobUrl = link || URL.createObjectURL(new Blob([data], settings)); newLink.setAt ...

Struggling with Debowerify in Grunt

After implementing debowerify in my project and configuring the transform in Gruntfile.js, I encountered an issue. Here's a snippet of the configuration: grunt.initConfig({ browserify: { app: { files: { 'publ ...

Expanding the content in Bootstrap Navbar

I am working with a bootstrap navbar and need to customize it by adding a SignOut button and a Welcome message to the menu bar. I also want to adjust the positioning of the logo and company/city name within the navbar. Here is the current setup of my navba ...

Tips for locking the button in the navigation bar while scrolling

I noticed that when I have 6 fields in my navbar, with 5 of them being links and one as a dropdown, the scrolling of the page causes all fields to remain fixed except for the dropdown field.Check out this image description for reference https://i.stack.im ...

Creating Divs that Adapt to Screen Size in HTML

I currently have images in my HTML with hard-coded height and width due to a required transition effect. However, these three images are placed within a div. Is there a way to set the container div to a specific responsive height and width that adjusts f ...

Display an AJAX div when the image is hovered over and have it track the movement of

I am seeking assistance with my website project, which involves providing users with download links to movies. However, I am struggling to make the preview_block div(id) appear when the mouse hovers over the movie_block div(id). Additionally, I am having ...

Setting up jade includes with gulp-jade: A comprehensive guide

Struggling with setting up Jade includes in your gulpfile.js while using gulp-jade? Check out this link for more information. Below is a snippet from the gulpfile.js: var gulp = require('gulp'); var browserSync = require('browser-s ...

Incorporate PNG files with pre-defined labels in a React element

In my application, there is a collection of PNG images with filenames consisting of only 2 letters like aa.png, ab.png, ac.png, and so on. Additionally, there is an API endpoint that retrieves an array of objects with a property "name" containing 3 letter ...

Troubleshooting the error message: "Uncaught TypeError: this.schedulerActionCtor is not a constructor" that occurs while executing the rootEpic in redux-

As I delve into learning how redux-observables work with typescript, I've been following a project example and referencing various guides like those found here and here. However, no matter what I try in setting up the epics/middleware, I keep encounte ...