3.1_使用渐变色及图案来填充文本
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用渐变色及图案来填充文本</title>
<style>
body{
background: #eee;
}
#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>
</body>
<script>
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var image = new Image();
var gradient = context.createLinearGradient(0,0,canvas.width,canvas.height);
var text = 'Canvas';
var pattern;
image.src = 'img/1.png';
context.font = '128px palatino';
context.strokeStyle = 'cornflowerblue';
context.shadowColor = 'rgba(0,0,0,0.8)';
context.shadowOffsetX = 5;
context.shadowOffsetY = 5;
context.shadowBlur = 10;
gradient.addColorStop(0,'blue');
gradient.addColorStop(0.25,'orange');
gradient.addColorStop(0.5,'white');
gradient.addColorStop(0.75,'red');
gradient.addColorStop(1.0,'yellow');
drawBackground();
drawGradientText();
image.onload = function (e){
pattern = context.createPattern(image,'repeat');
drawPatternText();
}
function drawBackground(){
context.save();
context.shadowColor = undefined;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.shadowBlur = 0;
var step_y = 12;
var left_margin = step_y*4;
var top_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.beginPath();
context.lineWidth = 1;
context.moveTo(left_margin,0);
context.lineTo(left_margin,canvas.height);
context.stroke();
context.restore();
}
function drawGradientText(){
context.fillStyle = gradient;
context.fillText(text,65,200);
context.strokeText(text,65,200);
}
function drawPatternText(){
context.shadowColor = undefined;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.shadowBlur = 0;
context.fillStyle = pattern;
context.fillText(text,65,350);
context.strokeText(text,65,350);
}
</script>
</html>