canvas 元素使用 JavaScript 在网页上绘制图像,本身是没有绘图能力。
canvas 是一个矩形区域,可以控制其每一像素。
canvas 拥有多种绘制路径、矩形、圆形、字符以及添加图像的方法。
下面来做几个示例:
1、填充画布
<canvas id=”myCanvas” width=”200″ height=”100″ style=”border:1px solid red;”></canvas>
<script type=”text/javascript”>
var c=document.getElementById(“myCanvas”);
var cxt=c.getContext(“2d”);
cxt.fillStyle=”#ccc”;
cxt.fillRect(5,10,150,60); //x,y,x,y
</script>
执行如下:
2、获取坐标
<script type=”text/javascript”>
function cnvs_getCoordinates(e){
x=e.clientX;
y=e.clientY;
document.getElementById(“xycoordinates”).innerHTML=”Coordinates: (” + x + “,” + y + “)”; }
function cnvs_clearCoordinates(){
document.getElementById(“xycoordinates”).innerHTML=””;}
</script>
<div id=”coordiv” style=”float:left;199px;height:99px;border:1px solid #c3c3c3″ onmousemove=”cnvs_getCoordinates(event)” onmouseout=”cnvs_clearCoordinates()”></div>
<div id=”xycoordinates”></div>
执行如下:
3、绘制线条、图形
1绘制正方形如下:
<canvas id=”myCanvas” width=”200″ height=”100″ style=”border:1px solid #c3c3c3;”>
您的浏览器不支持 canvas 标签.
</canvas>
<script type=”text/javascript”>
var c=document.getElementById(“myCanvas”);
var cxt=c.getContext(“2d”);
cxt.moveTo(10,10); //x,y 起点
cxt.lineTo(10,50); //x,y
cxt.lineTo(50,50); //x,y
cxt.lineTo(50,10); //x,y
cxt.lineTo(10,10); //x,y
cxt.stroke();
</script>
执行如下
2绘制圆形如下:
<canvas id=”myCanvas” width=”200″ height=”100″ style=”border:1px solid #c3c3c3;”>
你的浏览器不支持canvas
</canvas>
<script type=”text/javascript”>
var c=document.getElementById(“myCanvas”);
var cxt=c.getContext(“2d”);
cxt.fillStyle=”#ccc”;
cxt.beginPath();
cxt.arc(20,20,10,0,Math.PI*2,true);
cxt.closePath();
cxt.fill();
</script>
执行如下:
4、绘制渐变
<canvas id=”myCanvas” width=”200″ height=”100″ style=”border:1px solid #c3c3c3;”>
您的浏览器不支持 canvas 标签.
</canvas>
<script type=”text/javascript”>
var c=document.getElementById(“myCanvas”);
var cxt=c.getContext(“2d”);
var grd=cxt.createLinearGradient(0,0,175,50);
grd.addColorStop(0,”#000000″); //黑
grd.addColorStop(1,”#FFFFFF”); //白
cxt.fillStyle=grd;
cxt.fillRect(5,10,175,50);//x,y,x,y
</script>
执行如下:
5、图片
<canvas id=”myCanvas” width=”300″ height=”200″ style=”border:1px solid #c3c3c3;”>
您的浏览器不支持 canvas 标签.
</canvas>
<script type=”text/javascript”>
var c=document.getElementById(“myCanvas”);
var cxt=c.getContext(“2d”);
var img=new Image()
img.src=”aa.png”
cxt.drawImage(img,10,20); //x,y
</script>
执行如下:
最新评论