3.1_文本的描边与填充
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>文本的描边与填充</title>
<style>
body{
background: #eee;
}
#controls{
position: absolute;
left: 60px;
top: 25px;
}
#canvas{
background: #fff;
cursor: pointer;
margin-left: 10px;
margin-top: 10px;
box-shadow: 4px 4px 8px rgba(0,0,0,0.5);
-webkit-box-shadow: 4px 4px 8px rgba(0,0,0,0.5);
-moz-box-shadow: 4px 4px 8px rgba(0,0,0,0.5);
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="400"></canvas>
<div id="controls">
描边:<input type="checkbox" id="strokeCheckbox" checked="true" />
填充:<input type="checkbox" id="fillCheckbox" />
阴影:<input type="checkbox" id="shadowCheckbox" />
</div>
</body>
<script>
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var fillCheckbox = document.getElementById('fillCheckbox');
var strokeCheckbox = document.getElementById('strokeCheckbox');
var shadowCheckbox = document.getElementById('shadowCheckbox');
var text = 'HTML5';
context.font = '128px palatino';
context.lineWidth = 1.0;
context.fillStyle = 'cornflowerblue';
turnShadowsOn();
draw();
function turnShadowsOn(){
context.shadowColor = 'rgba(0,0,0,0.8)';
context.shadowOffsetX = 5;
context.shadowOffsetY = 5;
context.shadowBlur = 10;
}
function turnShadowsOff(){
context.shadowColor = undefined;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.shadowBlur = 0;
}
function draw(){
context.clearRect(0,0,canvas.width,canvas.height);
drawBackground();
if(shadowCheckbox.checked){
turnShadowsOn();
}else{
turnShadowsOff();
}
drawText();
}
function drawBackground(){
context.save();
turnShadowsOff();
var step_y = 12;
var top_margin = step_y*4;
var left_margin = step_y*3;
var i = canvas.height;
context.strokeStyle = 'lightgray';
context.lineWidth = 0.5;
while(i>top_margin){
context.beginPath();
context.moveTo(0,i);
context.lineTo(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,canvas.height);
context.stroke();
context.restore();
}
function drawText(){
var text_x = 65;
var text_y = canvas.height/2+35;
context.strokeStyle = 'orange';
if(fillCheckbox.checked){
context.fillText(text,text_x,text_y);
}
if(strokeCheckbox.checked){
context.strokeText(text,text_x,text_y);
}
}
fillCheckbox.onchange = draw;
strokeCheckbox.onchange = draw;
shadowCheckbox.onchange = draw;
</script>
</html>