首先,canvas
元素默认宽度为300px, 高度为150px,但是在开发过程中发现,直接在canvas
标签上设置样式,宽高似乎不太准确
// index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport">
<title></title>
<link rel="stylesheet" type="text/css" href="./index.css"/>
</head>
<body>
<canvas id="demo" style="width: 200px;height: 100px;border: 1px solid #000000;"></canvas>
<script src="./index.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
// index.js
var canvas = document.getElementById('demo');
var ctx = canvas.getContext('2d');
ctx.fillStyle = '#FF0000';
ctx.fillRect(0, 0, 100, 75);
然而,绘制出来尺寸明显不准确
可以通过以下方式设置:
方法一:
<canvas width="200" height="100"></canvas>
方法二:
var canvas = document.getElementById('demo');
canvas.width = 200;
canvas.height = 100;