我正在尝试创建一个包含3个画布的网页。画布应根据屏幕更改其大小。 我的方法只适用于一个画布(我指定ID的画布)。我使用的getElementByID只占用一个。每个画布都有自己的ID,但是具有相同的类名。所以我做了getElementByClassName,但它不能在其他屏幕上工作。大小保持默认大小(canvas标记中的大小) 然后我尝试使用querySelectorAll获取所有ID(因为它适用于1个id),但仍然无效。 拜托,请帮忙。 感谢。
function setCanvas() {
// using % of viewport for canvas bitmap (pixel ratio not considered)
var canvas = document.querySelectorAll("#BgCanvas, #SnakeCanvas, #Angel_PowerBallCanvas")
, vwWidth = window.innerWidth
, vwHeight = window.innerHeight
, percent = 60;
canvas.width = Math.round(vwWidth * percent / 100); // integer pixels
canvas.height = Math.round(vwHeight * percent / 100);
// not to be confused with the style property which affects CSS, ie:
// canvas.style.width = "60%"; // CSS only, does not affect bitmap
}
答案 0 :(得分:0)
使用getElementByClassName
尝试此示例,但您需要将其转换为数组,因为getElementByClassName
是HTML集合。
HTML
<canvas id="canvas1" class="canvas" ></canvas>
<canvas id="canvas2" class="canvas" ></canvas>
<canvas id="canvas2" class="canvas" ></canvas>
CSS
.canvas {width: 100px; height: 100px;border: 1px solid red; margin: 10px; float: left;}
SCRIPT
function setCanvas() {
// using % of viewport for canvas bitmap (pixel ratio not considered)
var canvas = document.getElementsByClassName("canvas")
, vwWidth = window.innerWidth
, vwHeight = window.innerHeight
, percent = 60;
var w = Math.round(vwWidth * percent / 100);
var h = Math.round(vwHeight * percent / 100);
// getElementByClassName("canvas") is a collection of HTML objects
// you'll need to convert the getElementByClassName into array by using [].slice.call()
[].slice.call(canvas).forEach(function(element) {
element.setAttribute("style", "height:" + h + "px;" + " width:" + w + "px;");
});
}
setCanvas();