87,917
社区成员
发帖
与我相关
我的任务
分享
<canvas id="cav" style="border:solid 1px #000;" width="600" height="400"></canvas>
<canvas id="cav" style="border:solid 1px #000;width:600px;height:400px;"></canvas>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>test</title>
</head>
<body>
<canvas id="cav1" style="border:solid 1px #000;" width="600" height="300"></canvas>
<br/><br/>
<canvas id="cav2" style="border:solid 1px #000;width:600px;height:300px;"></canvas>
<script type="text/javascript">
//正常
var can = document.getElementById("cav1");
var ctx=can.getContext('2d');
ctx.fillRect(10,10,200,100);
ctx.stroke();
//2倍
can = document.getElementById("cav2");
ctx=can.getContext('2d');
ctx.fillRect(10,10,200,100);
ctx.stroke();
</script>
</body>
</html>
ctx.fillRect(10,10,200,100);
的效果;而第二段代码中CSS代码把canvas默认长宽300 150(不包括容器边框)用类似图片放大的效果强制放大到600px 300px(边框应该是602 302),所以就是看到的样子了。
总结起来css中设置的长宽并非canvas的属性。而是对绘制出的图形进行缩放。如下面的代码:
<canvas id="cav2" style="border:solid 1px #000;width:600px;height:300px;" width="600"
height="300"></canvas>
CSS中的长宽和canvas中的长宽可同时存在。代码先处理canvas中的长宽属性确定容器大小以及ctx.fillRect(10,10,200,100);
的绘图大小,最后再执行CSS中的width和height设置,分别对长和宽进行缩放。