2016-09-14 8 views
0

コード私はランダムな四角形を生成したいキャンバスを持っています。私はちょうど私が幅、高さ、矩形の色を変更する方法を把握しようとしていることが

<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script> 
<script> 
window.onload { 
function rectWidth() { 
    var width = document.getElementById('Canvas').offsetWidth; 
    Math.floor((Math.random() * 100) + 1); 
} 
function rectHeight() { 
    var width = document.getElementById('Canvas').offsetHeight; 
    Math.floor((Math.random() * 200) + 2); 
} 
function randColor() { 
    var randomColor = Math.floor(Math.random()*16777215).toString(16); 
} 
return rectWidth; 
return rectHeight; 
return randColor; 
$(#rect).html("<rect width="return rectWidth;" height="return rectHeight" style=""color="return randColor"/>")} 
} 
</script> 
</head> 
<body> 
<canvas id="Canvas" width="900" height="200"> 
<rect id="rect" width="250" height="250" style="color=blue"/></canvas> 

を動作させるように見えることはできません。

次にポジションが来ます。

コードを変更して動作させるにはどうすればよいですか?キャンバス上に四角形を描画する方法の

+0

キャンバス上に描画する方法ではありません。キャンバスにhtmlを使って長方形を描画することはできません。それはjavascriptで行う必要があります。 –

+0

https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/rect –

+0

試しました。まだ動作しません。 http://codepen.io/PCMRwill0956/pen/LRNyyJ – will0956

答えて

0

例:

var canvas = document.getElementById("Canvas"); 
    var ctx = canvas.getContext("2d"); 
    ctx.beginPath(); 
    var width = 10; 
    var height = 10; 
    var x = 0; 
    var y = 0; 
    ctx.fillStyle = "#FFF0000"; 
    ctx.rect(x, y, width, height); 
    ctx.fill(); 
    ctx.stroke(); 

ここでキャンバスにランダムなサイズの、ランダムに色の四角形を描画し、迅速フィドルだ:https://jsfiddle.net/6omtu0pg/

+0

ちょうど試しました。私は キャッチしないTypeError:NULLのプロパティ 'getContext'を読み取ることができません Chromeで – will0956

+0

getElementByIdで使用しているIDが間違っているか、DOMが準備が整う前にコードが実行されています。これが別の無関係の問題であるため、さらに助けが必要な場合は、新しいコードを新しい質問に投稿してください。 –

関連する問題