1

我有这个画一个圆圈的代码。如何更改此代码以使红色圆圈为浏览器窗口的 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');
4

1 回答 1

1

考虑这个jsfiddle

load/ resize

然后用draw()then创建圆圈setVars()circle(...)

draw()(设置画布的宽度/高度)将清除画布(请参阅:如何清除画布以进行重绘

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();
于 2013-05-13T23:35:29.190 回答