【问题标题】:Can I specify canvas dimensions using vh and vw?我可以使用 vh 和 vw 指定画布尺寸吗?
【发布时间】:2015-10-17 21:43:28
【问题描述】:

我的代码是:

var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.canvas.width = 40vw;
ctx.canvas.height = 40vh;

它不起作用。在 JavaScript 中设置画布尺寸时可以使用 vw 和 vh 吗?如果有,怎么做?

【问题讨论】:

  • 您应该使用widthheight属性设置像素数,其值为整数。然后,您可以使用 CSS 对其进行扭曲。
  • @Oriol 这只是为我拉伸图像。如何将宽度和高度属性设置为视口的比例?
  • @Oriol 没关系,刚刚意识到我可以轻松地使用 document.documentElement.clientWidthdocument.documentElement.clientHeight 而不是使用 vw/vh

标签: javascript html html5-canvas


【解决方案1】:

我意识到我可以使用document.documentElement.clientWidthdocument.documentElement.clientHeight 分别计算出 vw 和 vh。

【讨论】:

    【解决方案2】:

    HTML:

    <canvas class="canvas_hangman"></canvas> 
    

    JS:

    function setUpCanvas() {
      canvas = document.getElementsByClassName("canvas_hangman")[0];
      ctx = canvas.getContext('2d');
      ctx.translate(0.5, 0.5);
    
      // Set display size (vw/vh).
      var sizeWidth = 80 * window.innerWidth / 100,
        sizeHeight = 100 * window.innerHeight / 100 || 766;
    
      //Setting the canvas site and width to be responsive 
      canvas.width = sizeWidth;
      canvas.height = sizeHeight;
      canvas.style.width = sizeWidth;
      canvas.style.height = sizeHeight;
    }
    
    window.onload = setUpCanvas();
    

    这完美地设置了您的 HTML 画布,以响应方式进行绘制。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-08
      • 2017-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多