HTML5画布调整为父级 [英] HTML5 canvas resize to parent

查看:143
本文介绍了HTML5画布调整为父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调整画布元素的大小,以使其适合其父级,无论是< body> (全屏)或一些< div> 。这是我的尝试:

I want to resize the canvas element so that if fits its parent, whether it's <body> ("full-screen") or some <div> for instance. 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?

请参阅这里的代码:
< a href =http://jsfiddle.net/ARKVD/24/ =noreferrer> http://jsfiddle.net/ARKVD/24/

推荐答案

最简单的做法是始终将画布保留在自己的div中。

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.

然后你可以使用CSS调整div,但是你想要的大小。你想要像身体一样大吗?给予div width:100%

Then you can use CSS to resize the div however you want. You want it as large as the body? Give the div width: 100%.

然后你可以随时做到:

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

如果你这样做,你不必担心你目前面临的奇怪问题当身体是div的直接父母。

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.

这篇关于HTML5画布调整为父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆