fillRect(100,100,100,100) 前2個100是指坐標(biāo),后2個100是指寬和高。
今天學(xué)習(xí)html5 的canvas,發(fā)現(xiàn)fillRect的坐標(biāo)和大小一直不對,研究了半天,發(fā)現(xiàn)canvas的寬度和高度必須內(nèi)聯(lián)在canvas標(biāo)簽中才對。郁悶了半天。
錯誤的方式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>
顯示結(jié)果:
正確的方式:
代碼如下:
<!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>
更多信息請查看IT技術(shù)專欄