http://jsbin.com/oMUtePo/1/edit
我一直在努力让 Canvas 填满整个页面。
我尝试使用...
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
它填充了宽度,但没有填充高度,画板画的是 1px 的线,这不是我想要的。
当在 CSS 中使用 100% 的宽度和高度时,宽度被缩放,高度被削减,当绘制它时,看起来光栅图像在 ms paint 中被缩放得很大,并且在 onmousedown 绘图上有一个很大的偏移量,这是显然不是我想要的。
如有任何帮助,我们将不胜感激。
完整代码:
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<title>HTML5 Canvas Drawing Board</title>
<style>
* {
margin: 0;
padding: 0;
}
body, html {
height: 100%;
}
#myCanvas {
cursor: crosshair;
position: absolute;
width: 100%;
height: 100%;
}
</style>
<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js?ver=1.4.2"></script>
<script type="text/javascript">
window.onload = function() {
var myCanvas = document.getElementById("myCanvas");
var curColor = $('#selectColor option:selected').val();
var ctx = myCanvas.getContext("2d");
ctx.fillStyle="#000";
ctx.fillRect(0,0,500,500);
if(myCanvas){
var isDown = false;
var canvasX, canvasY;
ctx.lineWidth = 5;
$(myCanvas)
.mousedown(function(e){
isDown = true;
ctx.beginPath();
canvasX = e.pageX - myCanvas.offsetLeft;
canvasY = e.pageY - myCanvas.offsetTop;
ctx.moveTo(canvasX, canvasY);
})
.mousemove(function(e){
if(isDown !== false) {
canvasX = e.pageX - myCanvas.offsetLeft;
canvasY = e.pageY - myCanvas.offsetTop;
ctx.lineTo(canvasX, canvasY);
ctx.strokeStyle = "white";
ctx.stroke();
}
})
.mouseup(function(e){
isDown = false;
ctx.closePath();
});
}
};
</script>
</head>
<body>
<canvas id="myCanvas">
Sorry, your browser does not support HTML5 canvas technology.
</canvas>
</body>
</html>
最佳答案
您必须在 Canvas 元素上设置以像素为单位的绝对大小,而不是像在演示中那样使用 CSS,因此首先从 CSS 规则中删除以下行:
#myCanvas {
cursor: crosshair;
position: absolute;
/*width: 100%; Remove these */
/*height: 100%;*/
}
然后将其添加到您的代码中 - 您需要使用 window
对象的 clientWidth/Height
。
myCanvas.width = window.innerWidth;
myCanvas.height = window.innerHeight;
var ctx = myCanvas.getContext("2d");
ctx.fillStyle="#000";
ctx.fillRect(0,0, myCanvas.width, myCanvas.height);
关于javascript - Canvas 填充页面宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18865817/