I created a canvas with a circle inside and filled it with a gradient.
I am not sure how to make the canvas as well as the circle inside the canvas responsive to the screen size.
I tried using vh
and vw
for the width and height of the canvas. But when I change the height or width of the window, the circle looks either too long or too wide.
Question:
I want the entire circle to decrease in size when the window size is reduced. I am not sure how to do this.
Code:
var c = document.getElementById('canvassun'); var ctx = c.getContext('2d'); var grd = ctx.createRadialGradient(85, 85, 20, 85, 85, 70); grd.addColorStop(0, 'red'); grd.addColorStop(0.5, 'orange'); grd.addColorStop(0.8, 'yellow'); grd.addColorStop(1, 'white'); ctx.beginPath(); ctx.fillStyle = grd; ctx.arc(90, 90, 70, 0, 2 * Math.PI); ctx.fill(); ctx.closePath;
#canvassun { height: 30vh; width: 14vw; border: 1px solid black; margin: 0 auto; display: block; margin-top: 18%; }
<canvas id="canvassun" width=170 height=170></canvas>
Listen to window resize event and redraw the canvas
function draw() {
var c = document.getElementById('canvassun');
var ctx = c.getContext('2d');
var grd = ctx.createRadialGradient(85, 85, 20, 85, 85, 70);
grd.addColorStop(0, 'red');
grd.addColorStop(0.5, 'orange');
grd.addColorStop(0.8, 'yellow');
grd.addColorStop(1, 'white');
ctx.beginPath();
ctx.fillStyle = grd;
ctx.arc(90, 90, 70, 0, 2 * Math.PI);
ctx.fill();
ctx.closePath;
}
window.addEventListener("resize", draw);
Note Probably you need to debounce the draw
function for performance
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.