【问题标题】:Why doesn't canvas work same or what is the difference between these codes? [duplicate]为什么画布工作不一样,或者这些代码之间有什么区别? [复制]
【发布时间】:2021-07-18 09:25:57
【问题描述】:

我是 JavaScript 新手。而且我不明白为什么代码不能正常工作。这是画布:

var canvas = document.getElementById("gameScreen");

var context = canvas.getContext("2d")

context.fillRect(20, 20, 20, 20);
#gameScreen {
  background-color:coral;
  width:200px;
  height:200px;
  }
<!--<canvas id = "gameScreen" width= "200" height= "200" style="background-color:coral"></canvas> -->

<canvas id = "gameScreen"></canvas>

这是另一幅画布:

var canvas = document.getElementById("gameScreen");

var context = canvas.getContext("2d");

context.fillRect(20, 20, 20, 20);
#gameScreen {
  background-color:coral;
  }
&lt;canvas id="gameScreen" width="200px" height="200px"&gt;&lt;/canvas&gt;

为什么第一个不能作为第二个??

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    默认画布尺寸为 300x150,当通过样式 (CSS) 设置尺寸时,它只会将其拉伸到该尺寸。

    首先要知道的是 canvas 元素有内在的 尺寸 = 内部坐标空间中的像素数(由 宽度和高度属性和属性)。它也有外在的 尺寸(style.width 和 style.height),它是 图像在网页内的像素。内在像素 被缩放以适应外部空间。

    来源:@yonran

    这里是一个例子,点击画布:

    var canvas = document.getElementById("gameScreen");
    
    var context = canvas.getContext("2d")
    
    context.fillRect(20, 20, 20, 20);
    #gameScreen {
      background-color:coral;
      transition: width 1s ease-in-out;
      width: 400px;
      height: 200px;
    }
    #gameScreen.small
    {
      width: 200px;
      height: 200px;
    }
    <!--<canvas id = "gameScreen" width= "200" height= "200" style="background-color:coral"></canvas> -->
    
    <canvas id = "gameScreen" onclick="this.classList.toggle('small')"></canvas>

    【讨论】:

      猜你喜欢
      • 2014-04-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      • 2021-04-19
      • 2011-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多