View Post
html5 canvas文本-字体的渐变色
像绘制图形时一样,在对文本进行填充及描边操作时,除了使用纯色,还可以使用图案及渐变色。如下图所示。
下面的代码创建了线性渐变色对象及填充图案对象。在图顶部的那行文本之前,应用程序先将填充样式属性设置为刚创建好的那个渐变色对象,同理,在绘制底部的文本前,应用程序也会先将填充样式属性设置为刚创建好的填充图案对象。
html代码:
1 <head> 2 <title>Filling Text with Gradients and Patterns</title> 3 <style> 4 body { 5 background: #eeeeee; 6 } 7 8 #canvas { 9 background: #ffffff; 10 cursor: pointer; 11 margin-left: 10px; 12 margin-top: 10px; 13 -webkit-box-shadow: 4px 4px 8px rgba(0,0,0,0.5); 14 -moz-box-shadow: 4px 4px 8px rgba(0,0,0,0.5); 15 box-shadow: 4px 4px 8px rgba(0,0,0,0.5); 16 } 17 18 #controls { 19 margin: 10px; 20 } 21 </style> 22 </head> 23 24 <body> 25 <canvas id=\'canvas\' width=\'950\' height=\'520\'> 26 Canvas not supported 27 </canvas> 28 29 <script src=\'example.js\'></script> 30 </body> 31 </html>
example.js代码:
1 var canvas = document.getElementById(\'canvas\'), 2 context = canvas.getContext(\'2d\'), 3 image = new Image(), 4 gradient = context.createLinearGradient(0, 0, 5 canvas.width, canvas.height), 6 text = \'Canvas\', 7 pattern; // create pattern after image loads 8 9 // Functions............................................................ 10 11 function drawBackground() { 12 var STEP_Y = 12, 13 TOP_MARGIN = STEP_Y*4, 14 LEFT_MARGIN = 35, 15 i = context.canvas.height; 16 17 context.save(); 18 19 context.strokeStyle = \'lightgray\'; 20 context.lineWidth = 0.5; 21 22 while(i > TOP_MARGIN) { // Draw horizontal lines from bottom up 23 context.beginPath(); 24 context.moveTo(0, i); 25 context.lineTo(context.canvas.width, i); 26 context.stroke(); 27 i -= STEP_Y; 28 } 29 30 // Draw vertical line 31 context.strokeStyle = \'rgba(100,0,0,0.3)\'; 32 context.lineWidth = 1; 33 34 context.beginPath(); 35 context.moveTo(LEFT_MARGIN, 0); 36 context.lineTo(LEFT_MARGIN, context.canvas.height); 37 context.stroke(); 38 39 context.restore(); 40 } 41 42 function drawGradientText() { 43 context.fillStyle = gradient; 44 context.fillText(text, 65, 200); 45 context.strokeText(text, 65, 200); 46 } 47 48 function drawPatternText() { 49 context.fillStyle = pattern; 50 context.fillText(text, 65, 450); 51 context.strokeText(text, 65, 450); 52 } 53 54 // Event Handlers....................................................... 55 56 image.onload = function (e) { 57 pattern = context.createPattern(image, \'repeat\'); 58 drawPatternText(); 59 }; 60 61 // Initialization....................................................... 62 63 image.src = \'redball.png\'; 64 65 context.font = \'256px Palatino\'; 66 context.strokeStyle = \'cornflowerblue\'; 67 68 if (navigator.userAgent.indexOf(\'Opera\') === -1) 69 context.shadowColor = \'rgba(100, 100, 150, 0.8)\'; 70 71 context.shadowOffsetX = 5; 72 context.shadowOffsetY = 5; 73 context.shadowBlur = 10; 74 75 gradient.addColorStop(0, \'blue\'); 76 gradient.addColorStop(0.25, \'blue\'); 77 gradient.addColorStop(0.5, \'white\'); 78 gradient.addColorStop(0.75, \'red\'); 79 gradient.addColorStop(1.0, \'yellow\'); 80 81 drawBackground(); 82 drawGradientText();