使用Canvas API 可以将一个图形重叠绘制在另外一个图形上,也可以给图形添加阴影效果。
1、Canvas 图形组合
通过 globalCompositeOperation = 属性 来指定重叠效果
<!DOCTYPE html> <html> <head> <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(50, 50, 30, 0, Math.PI*2,false); context.fill(); } </script> </head> <body onload="draw('canvas')"> <canvas id="canvas" width="500" height="500"></canvas> </body> </html>
2、给图形绘制阴影
相关属性:shadowOffsetX,shadowOffsetY,shadowOffsetColor,shadowBlur
<!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 = 10; context.shadowOffsetY = 10; context.shadowColor = "rgba(255,100,100,0.9)"; context.shadowBlur = 7.5; context.translate(0,50); for(var i=0;i<3;i++){ context.translate(70,100); create5Start(context); context.fill(); } } function create5Start(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++){ x = Math.sin(i*dig); 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="500" height="500"></canvas> </body> </html>
3、使用图像
有3中绘制方式:
context.drawImage(img,x,y)
context.drawImage(img,x,y,w,h)
context.drawImage(img,sx,sy,sw,sh,dx,dy,dw,dh)
<html> <head> <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, 100,100); // context.drawImage(image, 0,0,200,200); context.drawImage(image,100,100,200,200,100,100,100,100); } </script> </head> <body onload="draw('canvas')"> <canvas id="canvas" width="500" height="500"></canvas> </body> </html>