今天我在弄个html5的时候,发现,我已经在style里面设置了宽和高,但是当我输出canvas的 宽和高的时候,还是原来的默认的300px;和150px;
————————————————————————————————————
<!DOCTYPE HTML>
<html>
<head>
<title>canvas的宽和高的测试1</title>
<script>
function draw(){
var canvas=document.getElementById(“my”);
var context=canvas.getContext(“2d”);
context.beginPath();
//var width=canvas.getAttribute(“width”);
alert(canvas.width);
alert(canvas.height);
context.moveTo(100,100);
context.lineTo(0,0);
context.stroke();
}
window.addEventListener(“load”,draw,true);
</script>
</head>
<body>
<canvas id=”my” style=”width:100px;height:100px;border:solid 1px red;”></canvas>
</body>
</html>
————————————————————————————————————
看效果:
大家看到了吧!~ 这种结果显然是不对的!~
我在用第二中方法,分别设置其宽度和高度
输入代码:
————————————————————————————————————
<!DOCTYPE HTML>
<html>
<head>
<title>canvas的宽和高的测试1</title>
<script>
function draw(){
var canvas=document.getElementById(“my”);
var context=canvas.getContext(“2d”);
context.beginPath();
//var width=canvas.getAttribute(“width”);
alert(canvas.width);
alert(canvas.height);
context.moveTo(100,100);
context.lineTo(0,0);
context.stroke();
}
window.addEventListener(“load”,draw,true);
</script>
</head>
<body>
<canvas id=”my” width=”200px;” height=”200px;” style=”border:solid 1px red;”></canvas>
</body>
</html>
——————————————————————————————————————–
查看效果:
其实注意了,第一种设置不是canvas的高,而是canvas的style的高,需要使用canvas.style.height才能输出。
输入代码看看他们的区别:
————————————————————————————————————–
<!DOCTYPE HTML>
<html>
<head>
<title>canvas的宽和高的测试1</title>
<script>
function draw(){
var canvas=document.getElementById(“my”);
var context=canvas.getContext(“2d”);
context.beginPath();
alert(canvas.width);
alert(canvas.height);
alert(canvas.style.width);
context.moveTo(100,100);
context.lineTo(0,0);
context.stroke();
}
window.addEventListener(“load”,draw,true);
</script>
</head>
<body>
<canvas id=”my” width=”200″ height=”200″ style=”width:200px;height:200px;border:solid 1px red;”></canvas>
</body>
</html>
——————————————————————————————————————
查看效果: