[英]Make canvas with shape responsive
我創建了一個內部帶有圓圈的畫布,並為其填充了漸變。
我不確定如何根據屏幕尺寸制作畫布以及畫布內部的圓圈。
我嘗試使用vh
和vw
作為畫布的寬度和高度。 但是,當我更改窗口的高度或寬度時,圓看起來太長或太寬。
題:
當窗口尺寸減小時,我希望整個圓的尺寸減小。 我不確定該怎么做。
碼:
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>
聽窗口調整大小事件並重新繪制畫布
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);
注意可能需要抖了draw
性能功能
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.