canvas實現文字線性漸變效果程式碼例項

admin發表於2017-02-23

分享一段程式碼例項,它利用canvas實現了文字的線性漸變效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
#myCanvas {
  border: 3px solid deepskyblue;
  margin: 20px auto;
  display: block;
}
</style>
<script type="text/javascript">
window.onload=function(){
  var canvas = document.getElementById("myCanvas")
  var canvasObj = canvas.getContext("2d");
  canvasObj.beginPath();
  canvasObj.font = "50px serif";
  var linerG = canvasObj.createLinearGradient(100, 300, 200, 300);
 
  linerG.addColorStop(0.2, "red");
  linerG.addColorStop(0.4, "green");
  linerG.addColorStop(0.8, "blue");
  linerG.addColorStop(1, "orange");
 
  var str = "螞蟻部落";
  canvasObj.fillStyle = linerG;
  canvasObj.fillText(str, 100, 300);
}
</script>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
</body>
</html>

相關文章