fillRect(100,100,100,100) 前2個100是指坐標,後2個100是指寬和高。
今天學習Html5 的canvas,發現fillRect的坐標和大小一直不對,研究了半天,發現canvas的寬度和高度必須內聯在canvas標簽中才對。郁悶了半天。
錯誤的方式1:
復制代碼代碼如下:
<!doctype Html>
<Html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#mycanvas{
width: 200px;
height: 200px;
background: yellow;
}
</style>
</head>
<body>
<canvas id='mycanvas' ></canvas>
<script>
var c = document.getElementById('mycanvas');
var ctx = c.getContext("2d");
ctx.fillStyle='#f36';
ctx.fillRect(100, 100, 100, 100);
</script>
</body>
</Html>
錯誤的方式2:
復制代碼代碼如下:
<!doctype Html>
<Html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id='mycanvas' style='width:200px;height:200px;background:yellow'></canvas>
<script>
var c = document.getElementById('mycanvas');
var ctx = c.getContext("2d");
ctx.fillStyle='#f36';
ctx.fillRect(100, 100, 100, 100);
</script>
</body>
</Html>
顯示結果:
正確的方式:
復制代碼代碼如下:
<!doctype Html>
<Html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<canvas id='mycanvas' width='200px' height='200px' style='background:yellow'></canvas>
<script>
var c = document.getElementById('mycanvas');
var ctx = c.getContext("2d");
ctx.fillStyle='#f36';
ctx.fillRect(100, 100, 100, 100);
</script>
</body>
</Html>