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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.