我尝试在设备浏览器的宽度和高度中间画一个圆圈。但画布元素打扰了。如果我使画布足够大,圆形将在设备宽度和高度的中间绘制,但画布大小应该适合设备大小。
有没有办法让画布的宽度和高度适合设备的宽度和高度?
这就是解决方案:
<html>
<head>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1">
<style>
/* Remove padding and margin */
* {
margin:0;
padding:0;
}
html, body, .myCanvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id="myCanvas" class="myCanvas"/>
<script>
var canvas = document.getElementById('myCanvas');
var width = canvas.width;
var height = canvas.height;
var context = canvas.getContext('2d');
var centerX = width / 2;
var centerY = height / 2;
var radius = 70;
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#FF3300';
context.stroke();
console.log("width: " + width);
console.log("height: " + height);
</script>
</body>
</html>
答案 0 :(得分:1)
在获取画布后立即将其添加到您的代码中:
canvas.width = width;
canvas.height = height;
您还可以从html部分
中删除width
和height
属性
答案 1 :(得分:0)
使用css%size
HTML:
<canvas id="myCanvas" class="myCanvas"/>
CSS:
/* Remove padding and margin */
* {
margin:0;
padding:0;
}
html, body, .myCanvas {
width: 100%;
height: 100%;
}
修改强>:
获取画布的宽度/高度而不是窗口。
<html>
<head>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1">
<style>
/* Remove padding and margin */
* {
margin:0;
padding:0;
}
html, body, .myCanvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id="myCanvas" class="myCanvas"/>
<script>
var canvas = document.getElementById('myCanvas');
var width = canvas.width;
var height = canvas.height;
var context = canvas.getContext('2d');
var centerX = width / 2;
var centerY = height / 2;
var radius = 70;
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#FF3300';
context.stroke();
console.log("width: " + width);
console.log("height: " + height);
</script>
</body>
</html>