Javascript 如何将画布应用于整个文档或如何在整个文档上绘制?

Javascript 如何将画布应用于整个文档或如何在整个文档上绘制?,javascript,canvas,Javascript,Canvas,我有.aspx页面,我想用JS绘制整个文档。我是JS的新手。。。 例如,此代码(在我的aspx中)允许我在200x200区域上绘制: <canvas id="canvas" width="200" height="200"></canvas> <script type ="text/javascript"> $(document).ready(function () { ctx = document.getElementByI

我有.aspx页面,我想用JS绘制整个文档。我是JS的新手。。。 例如,此代码(在我的aspx中)允许我在200x200区域上绘制:

    <canvas id="canvas" width="200" height="200"></canvas>

    <script type ="text/javascript">
    $(document).ready(function () {
    ctx = document.getElementById('canvas').getContext('2d');       
    ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
    ctx.fillRect(30, 30, 55, 50);
    });
    </script>
JS:


没有办法在纸上画画。您需要使画布适合整个窗口,并在调整窗口大小时更新其大小(和重画)

如果在CSS中更改画布的大小,画布只会像图像一样拉伸。如果更改
宽度
高度
属性,则该属性将被清除

CSS:

守则:

function updateCanvas() {
    var $canvas = $("#canvas");
    $canvas.attr('width', $(document).width())
    $canvas.attr('height', $(document).height());
    var ctx = $canvas.get(0).getContext('2d');
    ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
    ctx.fillRect(30, 30, 55, 50);
}
$(window).on('resize', updateCanvas); // maybe, add some thresholding
updateCanvas();
UPD:刚刚提出了更高性能的解决方案:从
窗口设置画布大小。屏幕
并将其放入
溢出:隐藏
容器中,以适应整个窗口。这样,您就根本不需要重新绘制或调整画布大小(多显示器用户仍然可能是一个问题)

    #canvas {
    position: absolute;
    left: 0;
    top: 0;
    }
    function updateCanvas(width,height) {
    var $canvas = $("#canvas");
    $canvas.attr('width', $(document).width())
    $canvas.attr('height', $(document).height());
    var ctx = $canvas.get(0).getContext('2d');
    ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
    ctx.fillRect(0, 0, width, height/2);
    ctx.fillStyle = "rgba(0, 200, 0, 0.5)";
    ctx.fillRect(0, height/2, width, height);
    }

    $(document).ready(function () {
    updateCanvas($(document).width(), $(document).height())
    });
#canvas {
    position: fixed;
    left: 0;
    top: 0;
}
function updateCanvas() {
    var $canvas = $("#canvas");
    $canvas.attr('width', $(document).width())
    $canvas.attr('height', $(document).height());
    var ctx = $canvas.get(0).getContext('2d');
    ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
    ctx.fillRect(30, 30, 55, 50);
}
$(window).on('resize', updateCanvas); // maybe, add some thresholding
updateCanvas();