fillRect(100,100,100,100) 前2個(gè)100是指坐標(biāo),后2個(gè)100是指寬和高。
今天學(xué)習(xí)html5 的canvas,發(fā)現(xiàn)fillRect的坐標(biāo)和大小一直不對(duì),研究了半天,發(fā)現(xiàn)canvas的寬度和高度必須內(nèi)聯(lián)在canvas標(biāo)簽中才對(duì)。郁悶了半天。
錯(cuò)誤的方式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>
錯(cuò)誤的方式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>