simon simon - 11 months ago 41
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).



* { margin: 0; padding: 0;}

body, html { height:100%; }

canvas {
image-rendering: -moz-crisp-edges; /* Firefox */
image-rendering: pixelated; /* Chrome */


<!DOCTYPE html>
<link href="main.css" rel="stylesheet"</link>
<div id="wrapper">
<canvas id="ctx" width="256" height="144"></canvas>
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.fillStyle = "#FF6A6A";
ctx.fillRect(mouseX, mouseY, 16, 16);
setInterval(function (){
}, 40);

Thank you for any and all help.

Answer Source

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:


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


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