<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>por qué agrego 100 a x y espero que su posición sea (200,100) pero cuando abro en vivo la posición aún permanece (100,100)
Debido a que solo cambiará el valor de x, debe dibujarlo nuevamente en el lienzo y antes de dibujar nuevamente, debemos borrar el lienzo usando 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>