源码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>渐变色文本和图案文本</title> <style> body { background: #eeeeee; } #canvas { background: #ffffff; cursor: pointer; margin-left: 10px; margin-top: 10px; -webkit-box-shadow: 4px 4px 8px rgba(0,0,0,0.5); -moz-box-shadow: 4px 4px 8px rgba(0,0,0,0.5); box-shadow: 4px 4px 8px rgba(0,0,0,0.5); } #controls { margin: 10px; } </style> </head> <body> <canvas id='canvas' width='950' height='520'> Canvas not supported </canvas> <script> 'use strict'; let canvas = document.getElementById('canvas'), context = canvas.getContext('2d'), image = new Image(), gradient = context.createLinearGradient(0,0,canvas.width,canvas.height), text = 'Canvas', //在图片加载之后创建一个'模式' pattern; //Function…… /** * 画背景 */ let drawBackground=()=> { let STEP_Y = 12, TOP_MARGIN = STEP_Y * 4, LEFT_MARGIN = 35, i = context.canvas.height; context.save(); context.strokeStyle = 'lightgray'; context.lineWidth = 0.5; while (i > TOP_MARGIN) { // Draw horizontal lines from bottom up context.beginPath(); context.moveTo(0, i); context.lineTo(context.canvas.width, i); context.stroke(); i -= STEP_Y; } // Draw vertical line context.strokeStyle = 'rgba(100,0,0,0.3)'; context.lineWidth = 1; context.beginPath(); context.moveTo(LEFT_MARGIN, 0); context.lineTo(LEFT_MARGIN, context.canvas.height); context.stroke(); context.restore(); }; /** * 画渐变文本 */ let drawGradientText=()=>{ context.fillStyle=gradient; context.fillText(text, 65, 200); context.strokeText(text, 65, 200); }; /** * 画图案文本 */ let drawPatternText = () => { context.fillStyle = pattern; context.fillText(text, 65, 450); context.strokeText(text, 65, 450); }; //Event image.onload=()=>{ pattern=context.createPattern(image,'repeat'); drawPatternText(); }; //Init…… //添加图案 image.src = '../images/redball.png'; context.font = '256px Palatino'; context.strokeStyle = 'cornflowerblue'; context.shadowOffsetX = 5; context.shadowOffsetY = 5; context.shadowBlur = 10; //创建渐变 gradient.addColorStop(0,'blue'); gradient.addColorStop(0.25,'yellow'); gradient.addColorStop(0.5, 'white'); gradient.addColorStop(0.75, 'red'); gradient.addColorStop(1.0,'blue'); drawBackground(); drawGradientText(); </script> </body> </html>