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

Answers


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

Need Your Help

NSImage setImage: method causes memory leaks in ARC?

objective-c xcode memory-leaks automatic-ref-counting nsimageview

I am new in Apple developing (about 3 months) and now using Xcode 4.5.1 with ARC of all my projects.

Retrieve data from many to many relationship in asp.net mvc linq

asp.net-mvc linq entity-framework

I have problem retrieving data in many to many relationship using linq.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.