从上到下为HTML5 Circle添加渐变

时间:2013-06-06 11:41:23

标签: html5 canvas gradient

我正在尝试在HTML5画布中重新创建我的网站徽标,以获得一些乐趣并一路学习。到目前为止,我已经创建了基本的形状,但我不确定如何在圆圈上添加渐变,因此它从顶部的浅橙色到底部的深橙色。这就是我到目前为止所做的:

  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');
  var centerX = canvas.width / 2;
  var centerY = canvas.height / 2;
  var radius = canvas.width / 2 - 2;

  // circle
  context.beginPath();
  context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  context.fillStyle = '#FF9000';
  context.fill();
  context.lineWidth = 1;
  context.strokeStyle = '#FF9000';
  context.stroke();

  // top line
  context.beginPath();
  context.moveTo(canvas.width / 2 - canvas.width / 4, canvas.height / 2 - canvas.height / 4);
  context.lineTo(canvas.width / 2 + canvas.width / 4, canvas.height / 2 - canvas.height / 4);
  context.lineWidth = canvas.width / 7;
  context.strokeStyle = '#FFFFFF';
  context.lineCap = 'round';
  context.stroke();

  // short middle line
  context.beginPath();
  context.moveTo(canvas.width / 2 - canvas.width / 8, canvas.height / 2);
  context.lineTo(canvas.width / 2 + canvas.width / 8, canvas.height / 2);
  context.lineWidth = canvas.width / 7;
  context.strokeStyle = '#FFFFFF';
  context.lineCap = 'round';
  context.stroke();

  // bottom line
  context.beginPath();
  context.moveTo(canvas.width / 2 - canvas.width / 4, canvas.height / 2 + canvas.height / 4);
  context.lineTo(canvas.width / 2 + canvas.width / 4, canvas.height / 2 + canvas.height / 4);
  context.lineWidth = canvas.width / 7;
  context.strokeStyle = '#FFFFFF';
  context.lineCap = 'round';
  context.stroke();

有人可能会指导我如何做到这一点吗?就我对html等的知识而言,HTML5是一个相当大的飞跃,所以任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:1)

当您createLinearGradient将其视为绘制渐变将遵循的行时

// imaginary line goes from x1,y1 to x2,y2 (the gradient will go there also)
var gradient=createLinearGradient(  x1,y1,  x2,y2 );

如果您将此线条中心 - 顶部绘制到中心底部,则渐变将从上到下。

var orangeGradient = context.createLinearGradient(
    canvas.width/2, 0, canvas.width/2, canvas.height);

这是代码和小提琴:http://jsfiddle.net/m1erickson/LLGtc/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var context = canvas.getContext('2d');

    context.arc(canvas.width/2, canvas.height/2, canvas.width/2-2, 0, Math.PI*2,false);
    context.closePath();

    var orangeGradient = context.createLinearGradient(canvas.width/2, 0, canvas.width/2, canvas.height);
    orangeGradient.addColorStop(0, '#ffdd00');   
    orangeGradient.addColorStop(1, '#cc6600');
    context.fillStyle = orangeGradient;
    context.fill();


}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=400 height=400></canvas>
</body>
</html>