Why isn't my object updating its position when I input a new value?

<hmtl>
<head>
<!--<script src='main.js'></script>-->
</head>
<body>
<canvas id='myCanvas'> </canvas>
<script>
function shape(x,y){
this.x=x;
this.y=y;
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FF0000";
ctx.fillRect( this.x, this.y, 50, 50);
}
}
var sqr=new shape(100,100)
sqr.x+=100
</script>
</body>
</hmtl>

Despite adding 100 to x and expecting its position to be (200,100), when opening a live server it remains at the original position of (100,100).

Answer №1

When updating the value of x, it is necessary to redraw it on the canvas. Prior to redrawing, the canvas must be cleared using clearRect.

<html>
   <head>
      <!--<script src='main.js'></script>-->
   </head>
   <body>
      <canvas id='myCanvas'> </canvas>
      <script>
         function shape(x,y){
              this.x=x;
              this.y=y;
              var canvas = document.getElementById("myCanvas");
              var ctx = canvas.getContext("2d");
              this.draw = ()=>{
              ctx.clearRect(0, 0, canvas.width, canvas.height);
              ctx.fillStyle = "#FF0000";
              ctx.fillRect( this.x, this.y, 50, 50);
              ctx.stroke();
            }
         }
         var sqr=new shape(100,100)
         sqr.draw();
         sqr.x+=-100
         sqr.draw();
      </script>
   </body>
</html>

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

Provide JSON data on a designated pathway

I'm currently working on setting up a basic API that will respond with JSON data when accessed at the path /json The goal is to send back the object {"message": "Hello json"} in JSON format whenever a GET request is made to the /j ...

Guide to applying conditional styling to Material-UI TextField

After creating a custom MUI TextField, I implemented the following styling: const CustomDisableInput = styled(TextField)(() => ({ ".MuiInputBase-input.Mui-disabled": { WebkitTextFillColor: "#000", color: "#00 ...

I'm having trouble making my carousel smaller and centering it on the page. How can I adjust it to be a more subtle feature on the page?

I'm having trouble adjusting the width and height of my images in the code. Whenever I set them to less than 100%, it messes up the layout and the images get cropped. I want them centered without taking up so much space. I've resized all my imag ...

Determining if a path is within the same directory: a step-by-step guide

I need to check if the input path is located in the same folder or not Question: Is the input path in the same folder? For example, if my current path is f://learning/java and I am currently in a folder named java, then any path that directly belongs to ...

How can contextual binding be implemented in TypeScript?

In Laravel, you have the option to specify which class should be imported if a particular class is accessed. For example, if someone tries to use the Filesystem contract, it will return the Storage Facade (Laravel Contextual Binding). Similarly, if someo ...

What are the best practices for creating documentation in ReactJS?

I need to generate documentation in a .doc file format for each component defined in our ReactJS application. I am seeking an npm package that can assist with this process by extracting code and comments from my components and converting them into docume ...

Rails: How come my personalized stylesheet isn't taking priority over the font family?

I have included the Skeleton boilerplate css in my application from this source. It can be found within the directory app/assets/stylesheets. app/assets/stylesheets ├── application.css ├── custom.scss ├── normalize.css └── skeleton ...

Transfer information from the ajax success event to an external else/if statement

I am encountering an issue when trying to transfer the appropriate result from my ajax success function to an external function for further use. Currently, I am using user input to query a data source via ajax and receiving the object successfully. The re ...

Tips for displaying the Material UI Menu component on the left side instead of the default right side

Recently, I created a dropdown component using Material UI's Menu component. However, the default behavior of the menu is to open towards the right side. I actually need it to open towards the left instead. I attempted to modify its styling, and whil ...

Customizing the DatePicker with a unique button in material-ui

For my current project, I am utilizing a Datepicker component. I am looking to incorporate a custom information button in the upper right corner of the calendar layout, similar to the example image provided below: https://i.stack.imgur.com/fHMbn.png Unfo ...

The scrollbar is shifting the page's content towards the left

As a first-time user of Bootstrap, I have encountered an issue while building my website that I cannot seem to solve. Whenever I add large content that requires a scrollbar in the browser, the entire page shifts to the left. In simpler terms, when a scrol ...

Is there a way to create a timed fadeIn and fadeOut effect for a div using HTML and CSS?

I have a single div that initially displays text, and I want it to fade out after a specific time so that another div will then fade in. However, my attempt at coding this transition is not producing the desired result: $(function() { $(".preloa ...

Why is the Slick Slider displaying previous and next buttons instead of icons?

I'm currently working on creating a slider using the slick slider. Everything seems to be functioning properly, but instead of displaying arrows on the sides, it's showing Previous and Next buttons stacked vertically on the left side. It appears ...

A guide to implementing div wrapping in HTML

I'm in the process of using flexbox on my website. I have 10 div elements that I want to wrap around each other closely without any gaps between them. My goal is to have "4" positioned to the right of "1", instead of creating a new row and moving dow ...

Storing dates as collection names is not supported in Firestore

I'm currently facing an issue trying to store stock prices in Firestore. I want the structure to resemble something similar to SQL, like this: const d1 = new Date(); const result = d1.getTime(); console.log('Epochtime',result); database.coll ...

What could be causing the CSS issue following the recent webpack update?

I've taken on the task of updating an older VUE project with the latest npm packages. I managed to update everything successfully and get webpack to compile without any errors, but for some unknown reason, the CSS is no longer rendering in the browser ...

The div does not allow elements to be centered

I am facing an issue where elements are not centering on my div. I have tried numerous solutions (so many that I finally decided to create a Stack Overflow account), but nothing seems to work. Interestingly, the elements center on PC but for some reason, ...

What is the best way to prevent a strikethrough from appearing on the delete button in my JavaScript TO-Do application?

I'm working on coding a to-do app using JavaScript, HTML, and CSS. The issue I'm facing is that when I add the text-decoration: line-through property to the list items, it also affects the X icon used for deleting tasks. I suspect this problem ar ...

Tips for accessing the following element within an array using a for loop with the syntax for (let obj of objects)

Is there a way to access the next element in an array while iterating through it? for (let item of list) { // accessing the item at index + 1 } Although I am aware that I could use a traditional for loop, I would rather stick with this syntax. for (i ...

What is the best way to display information in a newly added row of a datatables table?

Working on ASP.NET gridview conversions with datatables.net plug-in. The reason behind this is complex and subject to debate. But, I need assistance with a specific issue. The process of converting the gridview using Javascript was simple and effective. H ...