画布填充页面宽度和高度

时间:2013-09-18 07:03:01

标签: javascript html css html5 canvas

http://jsbin.com/oMUtePo/1/edit

我一直在努力让画布填满整个页面。

我尝试过使用......

canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;

它填充了宽度,但不是高度,绘图板绘制了1px线,这不是我想要的。

当在CSS中使用100%的宽度和高度时,宽度被缩放,并且高度被剪切,当绘制它时看起来好像光栅图像在ms绘制中被缩放得明显更大并且在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>

1 个答案:

答案 0 :(得分:3)

您必须像在演示中一样在canvas元素上设置绝对大小(而不是CSS),因此首先从CSS规则中删除以下行:

#myCanvas {
    cursor: crosshair;
    position: absolute;
    /*width: 100%; Remove these */
    /*height: 100%;*/
}

然后将其添加到您的代码中 - 您需要使用clientWidth/Height对象的window

myCanvas.width = window.innerWidth;
myCanvas.height = window.innerHeight;

var ctx = myCanvas.getContext("2d");
ctx.fillStyle="#000";
ctx.fillRect(0,0, myCanvas.width, myCanvas.height);

<强> Your modified JSBIN