javascripthtmlcsscanvas

why my object don't change position when i add 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>

why i add 100 to x and hope its positon will be (200,100) but when i open live sever it position still remain (100,100)


Solution

  • Because it will only change the value of x, you have to draw it again on the canvas and before drawing again we have to clear canvas using clearRect

    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();
    <!DOCTYPE html>
    <html>
       <head>
          <!--<script src='main.js'></script>-->
       </head>
       <body>
          <canvas id='myCanvas'> </canvas>
       </body>
    </html>