15 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);
var context = canvas.getContext("2d");
context.fillStyle="#eeeeef";
context.fillRect(0,0,500,500);
context.shadowOffsetX = 20;
context.shadowOffsetY = 20;
context.shadowColor="rgba(100,100,100,0.5)";
context.shadowBlur = 3.5;
context.translate(0,50);
for(var i=0;i<3;i++)
{
context.translate(100,100);
createStar(context);
context.fill();
}
}
function createStar(context)
{
var dx=100;
var dy=0;
var s=50;
context.beginPath();
context.fillStyle="rgba(255,0,0,0.5)";
var x=Math.sin(0);
var y = Math.cos(0);
var dig=Math.PI/5*4;
for(var i=0;i<5;i++)
{
var x=Math.sin(i*dig);
var y=Math.cos(i*dig);
context.lineTo(dx+x*s,dy+y*s);
}
context.closePath();
}
</script>
</head>
<body onload="draw('canvas')">
<canvas id="canvas" width="500px" height="500px"></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");
context.fillStyle="#eeeeef";
context.fillRect(0,0,500,500);
image = new Image();
image.src="1.jpg";
image.onload=function()
{
drawImage(context,image);
}
}
function drawImage(context,image)
{
context.drawImage(image,0,0,200,200);
context.drawImage(image,270,270,380,380,230,230,100,100);
}
</script>
</head>
<body onload="draw('canvas')">
<canvas id="canvas" width="500px" height="500px"></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);
var context = canvas.getContext("2d");
var oprtns = new Array
(
"source-atop",
"source-in",
"source-out",
"source-over",
"destination-atop",
"destination-in",
"destination-out",
"destination-over",
"lighter",
"copy",
"xor"
);
i = 8;
context.fillStyle = "blue";
context.fillRect(10, 10, 60, 60);
context.globalCompositeOperation=oprtns[i];
context.beginPath();
context.fillStyle="red";
context.arc(60,60,30,Math.PI*2,false);
context.fill();
}
</script>
</head>
<body onload="draw('canvas')">
<canvas id="canvas" width="500px" height="500px"></canvas>
</body>
</html>


1914篇文章