Canvas绘图分享一:

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>	

                                                                                           效果如下: 


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值