Html5中canvas的一些使用
最近在研究HTML5,发现其中的canvas用途很广。不但可以绘制图形,还可以制作图片线性渐变,而且还能渲染文字做成特效。觉得挺有趣,于是把学习的内容记录起来了。
1.绘制圆形图
Html代码: <canvas id="roundness" width="600" height="300">
</canvas>
js代码: var canvas = document.getElementById("roundness");
var context = canvas.getContext("2d");
context.strokeStyle = "aqua";//圆形的颜色
context.lineWidth = "2";
context.beginPath();
context.arc(100,100,40,0,2*Math.PI); //40此值设置圆形的大小
context.stroke();
效果如下图:
2.绘制五角星
Html代码: <canvas id="canvasFive" width="600" height="250">
</canvas>
js代码: var canvas = document.getElementById("canvasFive");
var context = canvas.getContext("2d");
context.beginPath();
//设置是个顶点的坐标,根据顶点制定路径
for (var i = 0; i < 5; i++) {
context.lineTo(Math.cos((18+i*72)/180*Math.PI)*50+200,
-Math.sin((18+i*72)/180*Math.PI)*50+200);
context.lineTo(Math.cos((54+i*72)/180*Math.PI)*20+200,
-Math.sin((54+i*72)/180*Math.PI)*20+200);
}
context.closePath();
//设置边框样式以及填充颜色
context.lineWidth="3";
context.fillStyle = "red";
context.strokeStyle = "wheat";
context.fill();
context.stroke();
效果如下图:
3.绘制矩形
Html代码: <canvas id="canvasFour" width="600" height="200">
</canvas>
js代码:
var canvas = document.getElementById("canvasFour");
var context = canvas.getContext("2d");
context.rect(10,10,150,150);
context.lineWidth = 2;
context.fillStyle = "cyan"; //设置填充颜色
context.strokeStyle = "#F5270B"; //边框颜色
context.fill();
context.stroke();
效果如下图:
4.制作图片颜色线性渐变
Html代码: <canvas id="change" width="500" height="300">
</canvas>
js代码: var canvas = document.getElementById("line");
var context = canvas.getContext("2d");
var grd = context.createLinearGradient( 50 , 250, 500 , 800 );
grd.addColorStop(0,"white"); //设置颜色
grd.addColorStop(0.25,"blue"); //设置颜色
grd.addColorStop(0.5,"yellow"); //设置颜色
grd.addColorStop(0.75,"purple"); //设置颜色
grd.addColorStop(1,"black");
context.fillStyle = grd;
context.fillRect(50,250,500,800);
效果如下图:
5.画一条直线,长度可选。
Html代码: <canvas id="canvas" width="600" height="200">
</canvas>
js代码:
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.beginPath();
context.moveTo(100,100);
context.lineTo(600,100);
context.lineWidth = 2;
context.strokeStyle = "#F5270B";
context.stroke();
效果如下图: