<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>canvas</title>
<meta name="Keywords" content="">
<meta name="author" content="@my_programmer">
<style type="text/css">
body{margin:0;}
canvas{margin:20px;
/* 400px;
height: 300px;*/
}
</style>
</head>
<body onload="draw()">
<canvas id="canvas" width=400 height=300 style="border:1px solid #f00;"></canvas>
<script>
function draw() {
var canvas=document.getElementById('canvas');
var context=canvas.getContext('2d');
context.beginPath();
context.moveTo(20,20);
context.lineTo(200,100);
context.lineWidth=5;
context.stroke();
}
</script>
</body>
</html>
<html>
<head>
<meta charset="utf-8">
<title>canvas</title>
<meta name="Keywords" content="">
<meta name="author" content="@my_programmer">
<style type="text/css">
body{margin:0;}
canvas{margin:20px;
/* 400px;
height: 300px;*/
}
</style>
</head>
<body onload="draw()">
<canvas id="canvas" width=400 height=300 style="border:1px solid #f00;"></canvas>
<script>
function draw() {
var canvas=document.getElementById('canvas');
var context=canvas.getContext('2d');
context.beginPath();
context.moveTo(20,20);
context.lineTo(200,100);
context.lineWidth=5;
context.stroke();
}
</script>
</body>
</html>
1.宽:400;高:300;直接写在<canvas>里的效果:
2、删除<canvas>里的宽高,宽:400;高:300;写在<style>里的效果:
为什么两者的效果会不一样呢?
canvas跟其他标签一样,也可以通过css来定义样式。但这里需要注意的是:canvas的默认宽高为300px * 150px,在css中为canvas定义宽高,实际上把宽高为300px * 150px的画布进行了拉伸,如果在这样的情况下进行canvas绘图,你得到的图形可能就是变形的效果。所以,在canvas绘图时,应该在canvas标签里直接定义宽高。
另外就算写在内联样式里也是会有拉伸bug的:<canvas id="canvas" style=" 400px;height: 300px;"></canvas>
只能直接作为标签的属性写<canvas id="canvas" width="400px" height="300px"></canvas>,或者在js中动态更改