【问题标题】:why my object don't change position when i add value为什么当我添加值时我的对象不改变位置
【发布时间】:2022-01-01 10:07:29
【问题描述】:
<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>

为什么我在 x 上加 100 并希望它的位置是 (200,100) 但是当我打开 live sever 时它的位置仍然是 (100,100)

【问题讨论】:

    标签: javascript html css canvas


    【解决方案1】:

    因为它只会改变 x 的值,所以你必须在画布上再次绘制它,在再次绘制之前,我们必须使用 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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-07
      • 2022-11-13
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多