简体   繁体   English

HTML5画布调整为父级

[英]HTML5 canvas resize to parent

I want to resize the canvas element so that if fits its parent, whether it's <body> ("full-screen") or some <div> for instance. 我想调整canvas元素的大小,以便如果适合它的父元素,例如它是<body> (“全屏”)还是某些<div> This is my attempt: 这是我的尝试:

// called at each frame
function update() {
    var canvasNode = document.getElementById('mycanvas');
    canvasNode.width = canvasNode.parentNode.clientWidth;
    canvasNode.height = canvasNode.parentNode.clientHeight;
}

For some reason, the canvas doesn't stop growing! 出于某种原因,画布不会停止增长! Maybe client* aren't the right parameters? 也许client*不是正确的参数?

See the code in action here: http://jsfiddle.net/ARKVD/24/ 请参阅此处的代码: http//jsfiddle.net/ARKVD/24/

The easiest thing to do is to always keep the canvas in its own div. 最简单的方法是始终将画布保留在自己的div中。

The only thing that will ever be in this div is the canvas. 在这个div中唯一能做的就是画布。

Then you can use CSS to resize the div however you want. 然后你可以使用CSS来调整你想要的div。 You want it as large as the body? 你想要它和身体一样大吗? Give the div width: 100% . 给div width: 100%

Then you can always rightfully do: 然后你可以随时正确地做:

canvas.width = theDiv.clientWidth;
canvas.height = theDiv.clientHeight;

If you do this you won't have to worry about the weird issues that you're currently facing when the body is the direct parent of the div. 如果你这样做,你将不必担心当身体是div的直接父母时你正面临的奇怪问题。

I've found that the cleanest approach is to simply "remind" the canvas element how big it's supposed to be upon resize: 我发现最干净的方法是简单地“提醒”画布元素在调整大小时应该有多大:

window.onresize = function () {
    canvas.style.width = '100%';
    canvas.height = canvas.width * .75;
}

The height setting in this case is there to simply maintain a 4:3 ratio. 在这种情况下,高度设置只需保持4:3的比例。 You can, of course, make it 100% as well if you desire. 当然,如果你愿意,你也可以百分之百地做到这一点。

I found the same problem happening, and the only way I could find to work around it was to set the canvas height to parentHeight - 1. This was using CEF. 我发现同样的问题发生了,我找到解决它的唯一方法是将画布高度设置为parentHeight - 1.这是使用CEF。 In this fiddle I had to set it to parentHeight - 5. 这个小提琴中,我不得不将它设置为parentHeight - 5。

canvasNode.height = div.clientHeight - 5;

You can workaround the problem by breaking the circular dependency between the parent node and the child node. 您可以通过打破父节点和子节点之间的循环依赖关系来解决此问题。 The size allocation of the DOM elements should only propagate top-down (from the parent to the child). DOM元素的大小分配应该只从上到下传播(从父元素传播到子元素)。 You can ensure that the child element (canvas) does not affect the parent's size by setting 您可以通过设置确保子元素(画布)不会影响父元素的大小

canvasNode.style.position = 'absolute';

This puts it into its own document flow that is independent of the parent. 这将它放入自己独立于父级的文档流中。

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

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