14 HTML5 Canvas 绘制渐变图形网页前端/web开发工程师
1.绘制变形图形
代码示例:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script>
function draw(id)
{
var canvas = document.getElementById(id);
if(canvas==null)
{
return false;
}
var context =canvas.getContext("2d");
context.fillStyle="#eeeeef";
context.fillRect(0,0,500,500);
context.translate(200,50);
context.fillStyle="rgba(255,0,0,0.25)";
for(var i=0;i<50;i++)
{
context.translate(25,25);
context.scale(0.95,0.95);
context.rotate(Math.PI/10);
context.fillRect(0,0,100,50);
}
}
</script>
</head>
<body onload="draw('canvas')">
<canvas id="canvas" width="400px" height="400px"></canvas>
</body>
</html>
2.绘制渐变图形
代码示例:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script>
function draw(id)
{
var canvas = document.getElementById(id);
var context =canvas.getContext("2d");
var g1=context.createLinearGradient(0,0,0,300);
g1.addColorStop(0,"rgb(255,255,0)");
g1.addColorStop(0,"rgb(0,255,255)");
context.fillStyle=g1;
context.fillRect(0,0,500,500);
var g2=context.createLinearGradient(0,0,300,0);
g2.addColorStop(0,"rgba(0,0,255,0.5)");
g2.addColorStop(1,"rgba(255,0,0,0.5)");
for(var i=0;i<10;i++)
{
context.beginPath();
context.fillStyle=g2;
context.arc(i*25,i*25,i*10,0,Math.PI*2,true);
context.closePath();
context.fill();
}
}
</script>
</head>
<body onload="draw('canvas')">
<canvas id="canvas" width="400px" height="400px"></canvas>
</body>
</html>
3.绘制径向渐变
代码示例:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script>
function draw(id)
{
var canvas = document.getElementById(id);
if(canvas==null)
{
return false;
}
var context =canvas.getContext("2d");
var g1=context.createRadialGradient(400,0,0,400,0,400);
g1.addColorStop(0.1,"rgb(255,255,0)");
g1.addColorStop(0.3,"rgb(255,0,255)");
g1.addColorStop(1,"rgb(0,255,255)");
context.fillStyle=g1;
context.fillRect(0,0,500,500);
}
</script>
</head>
<body onload="draw('canvas')">
<canvas id="canvas" width="400px" height="400px"></canvas>
</body>
</html>


1914篇文章