user1615362
user1615362

Reputation: 3807

Drawing shape on canvas with relative size

I have this code that draws a circle. How do I change this code so that the red circle is 100% of the browser window? I want the red circle to resize with the browser window.

  <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');

Upvotes: 1

Views: 919

Answers (1)

MikeM
MikeM

Reputation: 27405

consider this jsfiddle

on load/resize:

create the circle with draw() then setVars() then circle(...)

draw() (which sets the width/height of the canvas) will clear the canvas (see: 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();

Upvotes: 1

Related Questions