javascript - 计算加载时 <canvas> 的大小?

标签 javascript html css canvas

<html>
<head>

<style type="text/css">
    canvas { width: 100%; height: 100%; }
</style>

<script>
    function init() {
        canvas = document.getElementById('canvas');
        alert(canvas.width + "x" + canvas.height);
    }
</script>

</head>

<body onload="init();">
    <canvas id="canvas"> </canvas>
</body>

</html>

此代码在设置样式之前显示尺寸。我需要样式后的尺寸。我该怎么做?

最佳答案

您的问题源于 Canvas 的固有尺寸与其占用的 CSS 像素数之间的差异。 HTML specification说:

The intrinsic dimensions of the canvas element equal the size of the coordinate space, with the numbers interpreted in CSS pixels. However, the element can be sized arbitrarily by a style sheet. During rendering, the image is scaled to fit this layout size.

这意味着根据用于绘制图像的坐标,您的 Canvas 默认为 300x150 像素的绘图空间。但是,您的 CSS 规则会将 Canvas 拉伸(stretch)到页面的大小(至少在宽度方面)。逻辑上仍然只有 300 像素的宽度可供绘制,但它会在对应的 100% 页面宽度上进行缩放和物理渲染。

无论如何,widthheight 属性对应于 Canvas 的固有绘图尺寸。由于您关心 CSS 大小,因此可以使用 window.getComputedStyle .

http://jsfiddle.net/3DDsX/

<head>
  <style>
    canvas { width: 100%; height: 100% }
  </style>
  <script>
    function init() {
      var canvas = document.getElementById('canvas');
      var style = getComputedStyle(canvas);
      alert(style.width + ' x ' + style.height);
    }
  </script>
</head>
<body onload="init();">
  <canvas id="canvas"></canvas>
</body>

关于javascript - 计算加载时 <canvas> 的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5140235/

相关文章:

javascript - 使用 JavaScript 从网站获取特定内容

javascript - 如何使用javascript从天数中获取月份和日期?

javascript - 自动检测输入并相应更改图像的 html 表单

css - 为什么我的两个 div 不能扩展包含 div 的整个高度?

html - 如果用户的系统字体大小增加(即字体大小 : 150% as recommended by the windows)

wordpress - 响应式页脚 CSS 问题

javascript - 调整窗口大小时禁用调整特定 div 的大小

javascript - jquery 方法调用没有 '()' 的对象方法?

javascript - 从范围输入( slider )获取值

css - 横向空体溢出