html5 <canvas>第二篇 strokeRect strokeStyle() strokeStyle() createLinearGradient addColorStop 用法 实心圆,空心圆,渐变

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<link href="css.css" rel="stylesheet" type="text/css">
<script type="text/javascript" language="jscript" src="js6.js"></script>
</head>

<body onLoad="pageload();">
<canvas id="cnvMain" width="200px" height="150px"; onClick="cnvClick();"></canvas>
</body>
</html>
 1 @charset "utf-8";
 2 /* CSS Document */
 3 
 4 body{
 5     font-size:36px;
 6 }
 7 canvas{
 8     border:dashed 1px #F00;
 9     cursor:pointer;
10 }
11 /*增加样式*/
12 p{
13     position:
14     absolute;
15     height:23px;
16     line-height:23px;
17     margin-left:10px;
18 }
19 span{
20     padding:3px;
21     border:solid 1px #033;
22     background-color:#00F;
23     cursor:pointer;
24     }

 

 1 // JavaScript Document
 2 function $$(id){
 3     return document.getElementById(id);
 4     
 5     }
 6     function pageload(){
 7         var cnv=$$("cnvMain");
 8         var ctx=cnv.getContext("2d");
 9         //设置边框
10         ctx.strokeStyle="#3ef3ed";
11         ctx.strokeRect(30,30,80,80);
12         //设置背景
13         ctx.fillStyle="#ccc";
14         ctx.fillRect(30,30,80,80);
15         }
16         function cnvClick(){
17             var cnv=$$("cnvMain");
18         var ctx=cnv.getContext("2d");
19         //清空图形
20         ctx.clearRect(36,36,50,50);
21             }

这个是绘制一个带边框的矩形

 

绘制矩形边框strokeRect(x,y,width,height);

参数为“x”,“y”为矩形的起点坐标,“width”“height”分别为矩形的宽和高

设置边框颜色strokeStyle();

清空图像中的颜色 clearRect();

绘制渐变颜色

1 var c=document.getElementById("myCanvas");
2 var ctx=c.getContext("2d");
3 
4 var grd=ctx.createLinearGradient(0,0,170,0);
5 grd.addColorStop(0,"black");
6 grd.addColorStop(1,"white");
7 
8 ctx.fillStyle=grd;
9 ctx.fillRect(20,20,150,100);
createLinearGradient(xStar, yStar,xEnd,YEnd)
xstar和ystar表示渐变开始的坐标
xEnd和YEnd表示渐变结束的坐标
addColorStop(value,color);表示渐变偏移量以及渐变颜色

绘制圆
var cnv=$$("cnvMain");
        var cxt=cnv.getContext("2d");
        //清除画布原有图形1
        cxt.clearRect(0,0,280,190);
        //开始画实心圆
        cxt.beginPath();
        cxt.arc(100,100,50,0,Math.PI*2,true);
        cxt.closePath();
        //设置填充背景色
        cxt.fillStyle="#3ef3ed";
        //进行填充
        cxt.fill();

各个参数的意思;

1.getContext(“2d”);返回一个用于在画布上绘图的环境

2.beginPath():声明开始绘制路径

3.closePath();绘制完图形后关闭绘制路径。

4.填充(画实心圆

1 //设置填充背景色
2         cxt.fillStyle="#3ef3ed";
3         //进行填充
4         cxt.fill();

描边(画空心圆

//设置边框色
        cxt.strokeStyle="black";
        
        //设置边框宽度
    cxt.lineWidth=5;
        //进行描边
        cxt.stroke();    

 

 
 来自w3c
 

 

posted @ 2017-03-12 11:04  943987243  阅读(2552)  评论(0编辑  收藏  举报