1、创建画布:
<canvas id="canvas" width="500" height="500" style="background:#eee;"></canvas>
注意:
1、画布宽,高只能使用HTML/JS属性来复制,不能使用CSS。
2、每个画布上有且只有一个画笔,进行绘图。
2、创建画笔:
<script>
var c=document.getElementById("canvas");
var ctx=c.getContext("2d");
</script>
3、绘制矩形:
<body>
<canvas id="canvas" width="350" height="200" style="background:#eee;"></canvas>
<script>
var c=document.getElementById("canvas");//获取画布
var ctx=c.getContext("2d");//创建画笔
ctx.lineWidth=2;//描边宽度
ctx.fillStyle="#C92027";//填充的样式
ctx.fillRect(50,50,100,100);//填充一个矩形,具上边距50px,左边距50px,宽高各100px
ctx.strokeStyle="#C92027"; //描边样式
ctx.strokeRect(200,50,100,100); //描边一个矩形
</script>
</body>
效果如下:
注意:
1、描边样式与描边矩形顺序不能颠倒,否则样式加载不出来,默认显示黑色
2、ctx.clearRect(x,y,w,h) 清除一个矩形范围内的绘图
4、绘制文本:
<body>
<canvas id="canvas" width="500" height="200" style="background:#eee;"></canvas>
<script>
var c=document.getElementById("canvas");
var ctx=c.getContext("2d");
ctx.textBaseline="top";//文本基线(取值alphabetic/top/bottom)
ctx.font="30px sans-serif";//文本大小和字体
ctx.fillStyle="red";//文本的样式
ctx.fillText("Web前端开发",80,40);//填充一段文本,距离画布的上边距80px,左边距40px
ctx.strokeStyle="red";//描边文本样式
ctx.strokeText("Web前端开发",80,80);//描边一段文本
ctx.fillStyle="blue";
ctx.fillText("width:"+ctx.measureText("web").width,40,120); // ctx.measureText(str)检测文本宽度
</script>
</body>
效果如下: