我有这个代码画一个圆圈。如何更改此代码以使红色圆圈是浏览器窗口的100%?我希望红色圆圈能够通过浏览器窗口调整大小。
<canvas width="100%" height="100%"></canvas>
var ctx;
function draw() {
ctx = $('canvas').get(0).getContext('2d');
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
}
function circle(x, y, r, c) {
ctx.beginPath();
var rad = ctx.createRadialGradient(x, y, 1, x, y, r);
rad.addColorStop(0, 'rgba('+c+',1)');
rad.addColorStop(1, 'rgba('+c+',0)');
ctx.fillStyle = rad;
ctx.arc(x, y, r, 0, Math.PI*2, false);
ctx.fill();
}
draw();
circle(128, 128, 200, '255,0,0');
答案 0 :(得分:1)
考虑这个jsfiddle
load
/ resize
:
使用draw()
然后setVars()
然后circle(...)
draw()
(设置画布的宽度/高度)将清除画布(请参阅:How to clear the canvas for redrawing)
var ctx, canvas, x, y, w, h, r;
function draw() {
ctx = $('canvas').get(0).getContext('2d');
canvas = ctx.canvas;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
function setVars() {
w = canvas.width;
h = canvas.height;
x = w/2;
y = h/2;
r = x < y ? x : y;
}
function circle(x, y, r, c) {
ctx.beginPath();
var rad = ctx.createRadialGradient(x, y, 1, x, y, r);
rad.addColorStop(0, 'rgba(' + c + ',1)');
rad.addColorStop(1, 'rgba(' + c + ',0)');
ctx.fillStyle = rad;
ctx.arc(x, y, r, 0, Math.PI * 2, false);
ctx.fill();
}
function makeCircle() {
draw();
setVars();
circle(x, y, r, '255,0,0');
}
$(window).resize(function () {
// redraw (onresize)
makeCircle();
});
// draw (onload)
makeCircle();