Reputation: 141
I've set up a canvas set up based on a tutorial but I need to make it responsive. At the moment I can resize the canvas if I change the viewport size and refresh but I need it to do it in real time.
HTML:
<canvas id="canvas" width="" height=""></canvas>
JS:
var canvas = document.querySelector('canvas');
canvas.width = window.innerWidth
canvas.height = window.innerHeight;
window.addEventListener('resize',() => {
canvas.setSize(window.innerWidth,window.innerHeight);
})
var c = canvas.getContext('2d');
//Rectangles
c.fillStyle = "rgba(255,0,0,0.2)"
c.fillRect(50, 100, 100, 100);
I've tried adding an EventListener but the console is giving me the following error:
Uncaught TypeError: canvas.setSize is not a function"
How would I get the EventListener to work?
Upvotes: 0
Views: 921
Reputation: 61
You can use something like that:
canvas.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
canvas.setSize
is really not a thing, so that's why you're getting TypeError.
Upvotes: 1