html5 canvas fillRect坐标和大小的问题解决方法
程序员文章站
2023-12-05 17:20:22
今天学习html5 的canvas,发现fillRect的坐标和大小一直不对,研究了半天,发现canvas的宽度和高度必须内联在canvas标签中才对... 14-03-26...
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>
今天学习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>