绘制响应画布,是100%的宽度和高度

drawing to responsive canvas that is 100% width and height

本文关键字:高度 100% 响应 绘制      更新时间:2023-09-26

我试图在大画布上获得跟随鼠标光标的形状。这段代码没有按预期工作。如果画布是屏幕的100%宽度/高度,我如何修改这个相对画布大小?

同样,我知道requestanimationframe,但为了演示这个问题,请忽略它(我正在使用它,但它是一个与本示例无关的复杂的计时混乱)。

小提琴:https://jsfiddle.net/gs5a4z84/

CSS:

* { margin: 0; padding: 0;}
body, html { height:100%; }
canvas {
    image-rendering: -moz-crisp-edges;    /* Firefox */
    image-rendering: pixelated;           /* Chrome */
    position:absolute;
    width:100%;
    height:100%;
}
HTML/JS:

<!DOCTYPE html>
<html>
    <head>
        <link href="main.css" rel="stylesheet"</link>
    </head>
    <body>
        <div id="wrapper">
            <canvas id="ctx" width="256" height="144"></canvas>
        </div>
        <script>    
            var mouseX, mouseY;
            const WIDTH = 256;
            const HEIGHT = 144;
            var ctx = document.getElementById('ctx').getContext('2d');
            ctx.canvas.addEventListener('mousemove', setMousePosition, false);
            function setMousePosition(e) {
                mouseX = e.clientX;
                mouseY = e.clientY;
            }
            function drawCursor() {
                ctx.clearRect(0,0,WIDTH,HEIGHT);
                ctx.fillStyle = "#FF6A6A";
                ctx.fillRect(mouseX, mouseY, 16, 16);
            }
            setInterval(function (){
                drawCursor();
            }, 40);
        </script>
    </body>
</html>

谢谢你的帮助。

如果你为画布对象使用CSS宽度和高度属性,那么你实际上不会改变画布上有多少像素,而是改变它的大小。要解决这个问题,使用JavaScript设置画布的宽度和高度属性:

JavaScript:

ctx.canvas.width = innerWidth;
ctx.canvas.height = innerHeight;
CSS:

body, canvas {
    margin: 0;
    padding: 0;
}