样式填充
fillStyle = color 颜色值
gradient 渐变色
image 图片
canvas 画布
video 视频
strokeStyle也适用
1、fillStyle = color可以填充任何css承认的颜色值
2、fillStyle = gradient 渐变色(线性渐变||镜像渐变)
var linearGrd = context.createLinearGradient( 50,50,300,300); linearGrd.addColorStop(0.0,"#fff"); linearGrd.addColorStop(0.5,"#ff0"); linearGrd.addColorStop(1.0,"#f00"); context.fillStyle = linearGrd; context.fillRect(0,0,800,800);
var radialGrd = context.createRadialGradient( 200,200,400,500,200,400); radialGrd.addColorStop(0.0,"#fff"); radialGrd.addColorStop(0.25,"#0f0"); radialGrd.addColorStop(0.5,"#ff0"); radialGrd.addColorStop(0.75,"#00f"); radialGrd.addColorStop(1.0,"#f00"); context.fillStyle = radialGrd; context.fillRect(0,0,800,800);
3、fillStyle = image||canvas||video
图片填充
<script type="text/javascript"> window.onload=function(){ var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); canvas.width = 1200; canvas.height = 800; var img = new Image(); img.src = "QQ截图20170116150903.png"; img.onload =function(){ var grd = context.createPattern(img,"repeat-x"); context.fillStyle = grd; context.fillRect(0,0,800,800); } } </script>
画布填充
<script type="text/javascript"> window.onload=function(){ var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); //添加另一个Canvas画布 var backCanvas = createBackgroundCanvas(); var pattern = context.createPattern(backCanvas,"repeat"); context.fillStyle = pattern; context.fillRect(0,0,800,800); } function createBackgroundCanvas(){ //document.createElement('canvas')这块是创造 var backCanvas = document.createElement('canvas'); backCanvas.width = 100; backCanvas.height = 100; var backCanvasContext = backCanvas.getContext('2d'); drawStar(backCanvasContext,50,50,50,0); return backCanvas; } function drawStar(cxt,x,y,R,rot) { cxt.save(); cxt.translate(x,y); cxt.rotate(rot/180*Math.PI); cxt.scale(R,R); starPath(cxt); cxt.fillStyle="#fb3"; cxt.fill(); cxt.restore(); } function starPath(cxt){ cxt.beginPath(); for(var i=0; i<5; i++){ cxt.lineTo(Math.cos((18+i*72)/180*Math.PI), -Math.sin((18+i*72)/180*Math.PI)); cxt.lineTo(Math.cos((54+i*72)/180*Math.PI)*0.5, -Math.sin((54+i*72)/180*Math.PI)*0.5); } cxt.closePath(); } </script>