simon simon - 2 months ago 6
CSS Question

drawing to responsive canvas that is 100% width and height

I am trying to get a shape to follow the mouse cursor on a large canvas. This code isn't working as expected. How can I modify this to the relative canvas size if the canvas is 100% width / height of the screen?

Also, I am aware of requestanimationframe, but for the purpose of demonstrating this issue, please ignore it (I'm using it but its a complicated mess of timings that aren't related to this example).

Fiddle: 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>


Thank you for any and all help.

Answer

If you use CSS width and height property for the canvas object, then you won't actually change how many pixels there are on the canvas, but how big it is. To fix your problem, set the canvas' width and height property using JavaScript:

JavaScript:

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

CSS:

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