簡體   English   中英

畫布填充頁面的寬度和高度

[英]Canvas Fill Page Width and Height

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>

您必須在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);

您修改后的JSBIN

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM