canvas宽高问题,已解决

js 设置 canvas 宽高为浏览器可用宽高,滚动条仍然出现,如下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CANVAS</title>
<style>
* {
padding: 0;
margin: 0;
}
html,
body {
height: 100%;
}
#canvas {
background-color: #cba;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
var canvas = document.getElementById('canvas');
canvas.width = document.body.clientWidth;
// canvas.width = window.innerWeight;
canvas.height = document.body.clientHeight;
// canvas.height = window.innerHeight;
context = canvas.getContext('2d');
context.beginPath();
context.arc(100, 100, 50, 0, 1.5 * Math.PI, true);
context.closePath();
context.strokeStyle = '#f0f';
context.stroke();
</script>
</body>
</html>

用一元素包裹一下即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.canvas-box {
/* IE兼容问题 */
/* display: flex; */
font-size: 0;
}
canvas {
background-color: #fcf;
}
</style>
</head>
<body>
<div class="canvas-box">
<canvas></canvas>
</div>
<script>
var canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
</script>
</body>
</html>
坚持原创技术分享,您的支持将鼓励我继续创作!