0

我正在尝试在 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 是一个很大的飞跃,因此我们将不胜感激。

4

1 回答 1

2

当您确实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>
于 2013-06-06T16:51:59.160 回答