源码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>文字的描边、填充、阴影</title> <style> body { background: #eeeeee; } #canvas { margin-left: 10px; -webkit-box-shadow: rgba(0, 0, 0, 0.2) 2px 2px 4px; -moz-box-shadow: rgba(0, 0, 0, 0.2) 2px 2px 4px; box-shadow: rgba(0, 0, 0, 0.2) 2px 2px 4px; border: 1px solid cornflowerblue; background: #ffffff; } #controls { margin: 10px; } </style> </head> <body> <div id='controls'> <input id='strokeCheckbox' type='checkbox' checked/>Stroke <input id='fillCheckbox' type='checkbox' checked/>Fill <input id='shadowCheckbox' type='checkbox' checked/>Shadow </div> <canvas id='canvas' width='600' height='220'> Canvas not supported </canvas> <script> 'use strict'; let canvas = document.getElementById('canvas'), context = canvas.getContext('2d'), fillCheckbox = document.getElementById('fillCheckbox'), strokeCheckbox = document.getElementById('strokeCheckbox'), shadowCheckbox = document.getElementById('shadowCheckbox'), //要展示的内容 text = 'HTML5'; //Function…… let draw = () => { context.clearRect(0, 0, canvas.width, canvas.height); drawBackground(); if (shadowCheckbox.checked) { turnShadowsOn(); } else { turnShadowsOff(); } drawText(); }; /** * 背景网格线 */ let drawBackground = () => { let STEP_Y = 12, TOP_MARGIN = STEP_Y * 4, LEFT_MARGIN = STEP_Y * 3, i = context.canvas.height; // 垂直线 context.strokeStyle = 'lightgray'; context.lineWidth = 0.5; while (i > TOP_MARGIN) { context.beginPath(); context.moveTo(0, i); context.lineTo(context.canvas.width, i); context.stroke(); i -= STEP_Y; } // 水平线 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(); }; let turnShadowsOn = () => { context.shadowColor='rgba(0,0,0,0.8)'; context.shadowOffsetX = 5; context.shadowOffsetY = 5; context.shadowBlur = 10; }; let turnShadowsOff = () => { context.shadowColor=undefined; context.shadowOffsetX = 0; context.shadowOffsetY = 0; context.shadowBlur = 0; }; let drawText = () => { let TEXT_X = 65, TEXT_Y = canvas.height / 2 + 35; context.strokeStyle = 'blue'; if (fillCheckbox.checked) context.fillText(text, TEXT_X, TEXT_Y); if (strokeCheckbox.checked) context.strokeText(text, TEXT_X, TEXT_Y); }; //Event…… fillCheckbox.onchange = draw; strokeCheckbox.onchange = draw; shadowCheckbox.onchange = draw; // Init context.font = '128px Palatino'; context.lineWidth = 1.0; context.fillStyle = 'cornflowerblue'; turnShadowsOn(); draw(); </script> </body> </html>