简体   繁体   English

为什么我将我的 canvas 宽度设置为 JS 中的 window innerWidth 和 canvas 宽度 100% 在 ZC7A628CBA2AEFA28EB61B7 中?

[英]Why do i have set my canvas width to window innerWidth in JS and canvas width 100% in css?

I don't get why I can't set the width and height to 100% in CSS OR set width and height to inner window width and height but, I have to do both.我不明白为什么我不能在 CSS 中将宽度和高度设置为 100%,或者将宽度和高度设置为内部 window 宽度和高度,但是我必须同时做这两个。 If I don't set both of them my canvas element won't show my drawing.如果我不同时设置它们,我的 canvas 元素将不会显示我的绘图。 Same thing with height too.身高也是一样。 Here's my code:这是我的代码:

<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>TESTING CANVAS DRAWING</title>
    <style>
      body {
        margin: 0px;
      }

      canvas {
        border: 2px soild black;
        width: 100%;
        height: 100%;
      }
    </style>
  </head>
  <body>
    <canvas>
      Your browser does not support the HTML5 canvas tag.
    </canvas>
    <script>
      //startup code
      let canvas = document.getElementsByTagName("canvas")[0];
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight

      //drawing

      let context = canvas.getContext("2d");
      context.fillRect(659, 327, 100, 100); // pixel coordinates start from the the top right
    </script>
  </body>
</html>

CSS and javascript, in this case, are referring to two separate sizes.在这种情况下,CSS 和 javascript 指的是两个不同的尺寸。 The Canvas element has it's own specific dimensions (default 300x150 i think) as well as the HTMLElement dimensions that can be controlled with CSS. Canvas 元素有它自己的特定尺寸(我认为默认为 300x150)以及可以用 CSS 控制的 HTMLElement 尺寸。 You can just set the dimensions in css and use relative values, eg:您可以在 css 中设置尺寸并使用相对值,例如:

      //startup code
      let canvas = document.getElementsByTagName("canvas")[0];
      //canvas.width = window.innerWidth;
      //canvas.height = window.innerHeight

      //drawing
      let x = 659 * canvas.width/ document.body.offsetWidth;
      let width = 100 * canvas.width / document.body.offsetWidth;
      let y = 327 * canvas.height / document.body.offsetHeight;
      let height = 100 * canvas.height / document.body.offsetHeight;
      let context = canvas.getContext("2d");
      context.fillRect(x, y, width, height); // pixel coordinates start from the the top right

I'm not setting the values but it should look the same if a little blurrier.我没有设置值,但如果有点模糊,它应该看起来一样。 Think of it as a monitor;把它想象成一个监视器; the CSS controls the physical size of the monitor and JS canvas dimensions are the resolution. CSS 控制显示器的物理尺寸,JS canvas 尺寸是分辨率。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM