2015-09-25 52 views
-2

我想只是做一個矩形,但沒有什麼會出現,只是背景。我已經試過ctx.fill,ctx.fillStyle等沒有什麼作品:Javascript沒有形狀出現

我指的這部分

fill(77, 66, 66); 
rect(10,200,100,100); 

下面是頁面

var ctx, W, H; 




window.onload = function() { 


    var canvas = document.getElementById("canvas"); 
    W = window.innerWidth; 
    H = window.innerHeight; 

    canvas.width = W; 
    canvas.height = H; 


    ctx = canvas.getContext("2d"); 


    setInterval(draw, 1); 


function draw() { 
    ctx.globalCompositeOperation = "source-over"; 
    ctx.fillStyle = "#E6E6FF"; // this part does appear 
    ctx.fillRect(0, 0, W, H); 

    fill(77, 66, 66); // this doesn't appear 
    rect(10,200,100,100); 

} 


} 

整個代碼由於

+2

它不應該是ctx.fill和ctx.rect? – toskv

+0

我也嘗試過這些(請參閱開始發佈) – zigg75483

+1

我認爲你應該[後退](http://stackoverflow.com/questions/32784673/javascript-not-showing-up-in-browser/32784727#32784727)並閱讀[畫布教程](http://www.html5canvastutorials.com/),@ zigg75483 – Scott

回答

0

你需要調用填補矩形在canv作爲上下文。 您還需要更改fillStyle否則您正在繪製一個與背景顏色相同的矩形,並且不會顯示。

var ctx, W, H; 
 

 

 

 
window.onload = function() { 
 

 

 
    var canvas = document.getElementById("canvas"); 
 
    W = window.innerWidth; 
 
    H = window.innerHeight; 
 

 
    canvas.width = W; 
 
    canvas.height = H; 
 

 

 
    ctx = canvas.getContext("2d"); 
 

 

 
    setTimeout(draw, 1); 
 

 

 
    function draw() { 
 
    ctx.globalCompositeOperation = "source-over"; 
 
    ctx.fillStyle = "#E6E6FF"; 
 
    ctx.fillRect(0, 0, W, H); 
 

 
    ctx.fillStyle = "red"; // need this otherwise the rect will be the same color as the background 
 
    ctx.rect(10, 200, 100, 100); // needs to be called on the canvas context 
 
    ctx.fill(); // needs to be called on the canvas context, it will fill any path not already filled in. 
 
    } 
 

 

 
}

0

你用相同的顏色填補這兩個領域,你必須使用上下文來進行填充功能。您還需要在填充之前創建矩形。

試試這個關於大小:https://jsfiddle.net/szbk6f67/3/

var ctx, W, H; 

window.onload = function() { 

    var canvas = document.getElementById("canvas"); 
    W = 400; 
    H = 400; 

    canvas.width = W; 
    canvas.height = H; 

    ctx = canvas.getContext("2d"); 

    setInterval(draw, 1); 

    function draw() { 
     ctx.globalCompositeOperation = 'source-over'; 
     ctx.fillStyle = 'gray'; 
     ctx.fillRect(0, 0, W, H); 

     ctx.fillStyle = 'black'; 
     ctx.rect(10, 200, 100, 100); 
     ctx.fill(); 
    } 
}