gpt4 book ai didi

javascript - 如何使用 JavaScript 调整 Canvas 大小?

转载 作者:太空宇宙 更新时间:2023-11-04 13:51:27 26 4
gpt4 key购买 nike

如何使 JavaScript Canvas (或 400 像素 x 400 像素绘图区域的任何名称)大于 400x400?

我有一个 1440p 的屏幕,当我通过 HTML 文件运行我的 JS 文件时, Canvas 在左上角是一个 400px x 400px 的小框并不奇怪。

我可以做些什么来将 Canvas 扩展到指定的高度和宽度吗?

最佳答案

以下 jsfiddle 演示了如何调整 Canvas 大小。 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>

关于javascript - 如何使用 JavaScript 调整 Canvas 大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39563033/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com