如何使用JavaScript调整画布大小?

5

如何将JavaScript画布(或称为400x400绘图区域)扩大到超过400x400?

我有一个1440p的屏幕,当我通过HTML文件运行我的JS文件时,画布不出所料地是一个位于左上角的小型400x400的框。

有没有什么方法可以将画布扩展到指定的高度和宽度?


请提供您的代码或创建一个 jsfiddle,以便我们可以处理您的代码。或者告诉您的问题。 - Baezid Mostafa
5个回答

15
以下jsfiddle演示如何调整画布大小。https://jsfiddle.net/intrinsica/msj0cwx3/

(function() {
  var canvas = document.getElementById('canvas'),
      context = canvas.getContext('2d');

  // Event handler to resize the canvas when the document view is changed
  window.addEventListener('resize', resizeCanvas, false);

  function resizeCanvas() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;

    // Redraw everything after resizing the window
    drawStuff(); 
  }
  resizeCanvas();

  function drawStuff() {
    // Do drawing here
    context.strokeRect(10,10, 230,100);
    context.font = '16px serif';
    context.fillText('The canvas is the blue', 30, 30);
    context.fillText('background color seen here.', 30, 50);
    context.fillText('It will resize if the window', 30, 70);
    context.fillText('size is adjusted.', 30, 90);
  }
})();
* { margin:0; padding:0; } /* to remove the top and left whitespace */

html, body { width:100%; height:100%; } /* just to be sure these are full screen*/

canvas {
    background: #77f;  /* to show the canvas bounds */
    display:block;     /* to remove the scrollbars */
}
<canvas id="canvas"></canvas>


1
你是否通过HTML声明了一个画布?如果是,你可以使用以下代码:
<canvas id="myCanvas" width="1400" height="900"></canvas>

如果您想通过Javascript更改大小,可以使用以下代码:
<script type="text/javascript">
    document.getElementById('myCanvas').height = 800;
    document.getElementById('myCanvas').width = window.innerWidth;
</script>

-1

由于Javascript可能会忽略CSS,因此请尝试在Javascript和CSS中设置画布的宽度和高度。例如,如果您的id叫做canvas,并且还要在canvas标签中添加宽度和高度,那么我想让我的画布宽度为650px,高度为750px。

canvas.width = 650px;
canvas.height = 750px;

-1

Canvas元素就像任何标准的DOM对象一样。因此,您可以使用标准CSS调整画布的大小:

<canvas />
<style>
canvas {
  width: 100%;
  min-height: 400px;
}
</style>

https://jsfiddle.net/z3pL9qp9/


画布很容易改变形状;但你需要重新绘制内容,以确保你已经考虑到了尺寸的变化。


-1
如果您在项目中使用Processing.JS,我可以提供帮助。不确定它是否适用于普通JavaScript,但是值得一试。
size(screenHeight, screenWidth);

如果您想要自动检测屏幕尺寸,可以像这样实现。
var screenSizeH = screen.height;

或者

var screenSizeW = screen.width;

你可能会遇到问题。因为调整画布大小只是调整画布本身,而不是其中的任何内容。

解决这个问题的方法是将所有内容乘以一个比例。

var scaless = screenSize/400;

如果是正方形,您需要将每个尺寸都乘以比例尺。对于高度和宽度,您需要分别制作两个比例尺。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接