我正在研究一个小型网页,该网页会根据用户输入生成图形。我计划在canvas
代码中放置一个html
,并使用javascript
创建图像。我遇到的问题是,在canvas
文件中定义的css
大小似乎只能缩放一个小的canvas
,而不能实际创建一个更大的。这是我的html
代码
function test() {
var canvas = document.getElementById("canvas");
if (null == canvas || !canvas.getContext) return;
ctx = canvas.getContext("2d");
for (var i = 0; i <= canvas.width; i += 50) {
for (var j = 0; j < canvas.height; j += 20) {
ctx.fillText(j, i, j);
}
}
}
body {
background-color: rgba(0, 100, 100, 0.2);
width: 100%;
}
canvas {
width: 100%;
}
<html>
<head>
<meta charset="utf-8">
<title>
Test
</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0,
maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" href="css/styles.css">
<script language="javascript" type="text/javascript" src="js/worker.js">
</script>
</head>
<body onload="test()">
<canvas id="canvas"></canvas>
</body>
</html>
输出看起来像这样(当我将
width
文件中canvas
的css
替换为100%
时,也会发生同样的情况)为什么我不会得到较小的数字,达到700?
最佳答案
您的神秘宽度和高度来自缺少width
和height
属性的画布默认值。这些默认值是宽度300和高度150。在HTMLCanvasElemnet here上阅读更多内容。
要更正此行为,可以使用这些属性为它提供静态的宽度和高度(不理想),也可以使用javascript设置宽度和高度。我建议使用offsetWidth
和offsetHeight
属性。每当窗口调整大小时,也有必要设置这些值。这可以通过事件监听器来完成。这是一个演示:
https://jsfiddle.net/f7btghdr/2/
var canvas = document.getElementById("canvas");
ctx=canvas.getContext("2d");
function test() {
for (var i=0; i <= canvas.offsetWidth; i += 50){
for (var j=0; j <= canvas.offsetHeight; j += 20){
ctx.fillText(i + 'x' + j,i,j);
}
}
}
function adjustCanvas() {
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.textBaseline="top";
test();
}
window.addEventListener('resize', adjustCanvas);
adjustCanvas();
html, body, canvas {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
display: block;
}
<canvas id="canvas"></canvas>
编辑
根据Kaiido在下面的评论,以下代码段可能是一种更好的方法。值得注意的是,
clearRect
调用是多余的,getBoundingClientRect
应该为画布的宽度和高度提供更精确的值,并且画布CSS也是不必要的(它被width
和height
属性覆盖了)无论如何)。以下是修改后的演示,其中包含了这些更改。var canvas = document.getElementById("canvas");
ctx=canvas.getContext("2d");
function test() {
for (var i=0; i <= canvas.offsetWidth; i += 50){
for (var j=0; j <= canvas.offsetHeight; j += 20){
ctx.fillText(i + 'x' + j,i,j);
}
}
}
function adjustCanvas() {
var dimensions = canvas.parentNode.getBoundingClientRect();
canvas.width = dimensions.width;
canvas.height = dimensions.height;
ctx.textBaseline="top";
test();
}
window.addEventListener('resize', adjustCanvas);
adjustCanvas();
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
display: block;
}
.canvas-wrapper {
width: 100%;
height: 100%;
overflow: hidden;
}
canvas {
display: block;
}
<div class="canvas-wrapper">
<canvas id="canvas"></canvas>
</div>