2013-05-13 64 views
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'); 
+0

這已經失敗; '('canvas')。get(0).getContext('2d');'試着先解決你所有的錯誤:) – 2013-05-13 22:13:59

+0

square not round;)ctx = $('canvas')。get [0]。的getContext( '2D'); – markE 2013-05-13 22:33:39

回答

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