带有HTML5画布元素的矩形渐变 [英] Rectangular Gradient with HTML5 Canvas Element

查看:105
本文介绍了带有HTML5画布元素的矩形渐变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用HTML5 canvas元素绘制具有渐变效果的矩形(如下图所示)?

How can I draw a rectangle with a gradient effect like the one pictured below using the HTML5 canvas element?

编辑:感谢所有反馈。是的,我已经尝试了许多方法。例如,是否可以按照@Loktar的建议使用 createRadialGradient 方法?以下是一些示例代码:

Thanks for all the feedback. Yes, I have already tried many methods. For example, can I use the createRadialGradient method as @Loktar suggests? Here is some sample code:

<html>
  <head>
    <title>test</title>
      <script type="application/x-javascript">
        function draw() {
          var canvas = document.getElementById("canvas"),
          ctx = canvas.getContext("2d");

          var grad1 = ctx.createRadialGradient(50, 50, 0, 50, 50, 50);
          grad1.addColorStop(0, 'rgba(255, 252, 0, 1)');
          grad1.addColorStop(1, 'rgba(68, 205, 37, 1)');

          ctx.fillStyle = grad1;
          ctx.fillRect(0, 0, 100, 100);
       }
    </script>
  </head>
  <body onload="draw();">
    <div>
      <canvas id="canvas" width="100" height="100"></canvas>
    </div>
  </body>
</html>

但是结果并不是我想要的:

But the result is not quite what I want:

应该这样做使用GDI +提供的 PathGradientBrush 这样的方法很容易。
我不确定HTML5 canvas元素是否可能。

This should be done easily with a method like PathGradientBrush provided by GDI+. I'm not sure is it possible with the HTML5 canvas element.

推荐答案

您可以尝试使用组合线性渐变和裁剪。 演示。代码:

You could try to use a combination of linear gradient and clipping. Demo. Code:

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

var outerColor = 'rgba(68,205,37,1)';
var innerColor = 'rgba(255,252,0,1)';

var w = 200;
var h = 50;
canvas.width = w;
canvas.height = h;

function gradient(dir) {
    var grad = ctx.createLinearGradient(dir[0], dir[1], dir[2], dir[3]);

    grad.addColorStop(0, outerColor);
    grad.addColorStop(0.5, innerColor);
    grad.addColorStop(1.0, outerColor);

    return grad;
}

// idea: render background gradient and a clipped "bow"
function background() {
    ctx.fillStyle = gradient([0, 0, 0, h]);
    ctx.fillRect(0, 0, w, h);
}

function bow() {
    ctx.save();

    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(w, h);
    ctx.lineTo(w, 0);
    ctx.lineTo(0, h);
    ctx.clip();

    ctx.fillStyle = gradient([0, 0, w, 0]);
    ctx.fillRect(0, 0, w, h);

    ctx.restore();
}

background();
bow();

这篇关于带有HTML5画布元素的矩形渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆