有没有办法创建一个动态画布,其尺寸与它所在的<div>
相同。
我在画布的CSS中用height: 100%, width: 100%
试了一下。比我的画布总是像div BUT 一样,它内容的内容可以扩展为。
所以我想知道一种调整画布大小的方法,但即使我改变了移动设备上的风景,也要保持图像的确切位置。
答案 0 :(得分:1)
您想要设置canvas元素的宽度和高度属性,而不是仅拉伸画布的css宽度和高度,默认为300x150宽度/高度。您可以使用JavaScript动态调整canvas元素的大小。
这是一个有效的例子。
//get the elements
const canvas = document.getElementById("canvas");
const myDiv = document.getElementById("my-div");
//set the width and height attributes to the div width and height
function resize(){
canvas.width = myDiv.clientWidth;
canvas.height = myDiv.clientHeight;
}
//on page resize, call resize()
window.addEventListener("resize", resize, false);
//call resize() initially to set the canvas size correctly
resize();
//you can call resize() when your div changes size, dynamically resizing the canvas to the div
div {
width: 50vw;
height: 50vh;
background-color: lightblue;
}
canvas {
background-color: rgba(255,0,0,0.5);
}
<div id="my-div">
<canvas id="canvas"></canvas>
</div>
答案 1 :(得分:0)
要调整画布大小,您可以使用HTML5画布标记。骨架下面是需要可调整大小的画布的应用程序所需的一切。它:
示例代码:
<html>
<body>
<head>
<meta charset="utf-8">
<title>Resize HTML5 canvas dynamically</title>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0px;
border: 0;
overflow: hidden; /* Disable scrollbars */
display: block; /* No floating content on sides */
}
</style>
</head>
<body>
<canvas id='c' style = 'position: absolute; left: 0px; top: 0px;' >
</canvas>
<script>
(function() {
var
// Obtain a reference to the canvas element
// using its id.
htmlCanvas = document.getElementById('c'),
// Obtain a graphics context on the
// canvas element for drawing.
context = htmlCanvas.getContext('2d');
// Start listening to resize events and
// draw canvas.
initialize();
function initialize() {
// Register an event listener to
// call the resizeCanvas() function each time
// the window is resized.
window.addEventListener('resize', resizeCanvas, false);
// Draw canvas border for the first time.
resizeCanvas();
}
// Display custom canvas.
// In this case it's a blue, 5 pixel border that
// resizes along with the browser window.
function redraw() {
context.strokeStyle = 'blue';
context.lineWidth = '5';
context.strokeRect(0, 0, window.innerWidth, window.innerHeight);
}
// Runs each time the DOM window resize event fires.
// Resets the canvas dimensions to match window,
// then draws the new borders accordingly.
function resizeCanvas() {
htmlCanvas.width = window.innerWidth;
htmlCanvas.height = window.innerHeight;
redraw();
}
})();
</script>
</body>
</html>