【问题标题】:Image gradient on HTML5 canvasHTML5 画布上的图像渐变
【发布时间】:2011-09-19 11:18:12
【问题描述】:

我想在图像上获得径向渐变效果(alpha = 1 在中间,边缘透明)。

你有什么想法吗?

【问题讨论】:

标签: javascript gradient html5-canvas


【解决方案1】:

如果我没记错你想要做的是:

  1. 绘制图像
  2. 在其上绘制径向渐变,其中边框透明,中间不透明,并使用上下文中的globalCompositeOperation 设置将透明渐变与图像混合。

您可以轻松地将其转换为代码:http://jsfiddle.net/W8Ywp/1/

var ctx = $('#cv').get(0).getContext('2d');

var img = new Image();

img.src = 'http://www.netstate.com/states/'
        + 'symb/flowers/images/oklahoma_rose.jpg';

img.onload = function() {
    ctx.drawImage(img, 0, 0, 300, 300); // Draw image

    // Create gradient, from middle to borders
    var gradient = ctx.createRadialGradient(150, 150, 0,
                                            150, 150, 150);

    // Opaque white in the middle
    gradient.addColorStop(0, 'rgba(255,255,255,0)');

    // Transparent white at the borders
    gradient.addColorStop(1, 'rgba(255,255,255,1)');

    ctx.globalCompositeOperation = 'destination-out';
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, 300, 300); // Fill rectangle over image with the gradient
};

【讨论】:

  • 这不是我想要的解决方案。我想将图像添加到另一个图像上,因此它可以平滑融合。如果我将渐变从白色透明变为白色不透明,图像将具有渐变,但边缘不会透明,它将是白色的。
  • @gabitzish 与whatwg.org/specs/web-apps/current-work/multipage/… 一起玩ctx.globalCompositeOperation 设置可能会解决这个问题。
  • 这就是我想要的!谢谢 Alnitak!
  • 优秀的@Alnitak 谢谢!这应该是这篇文章和stackoverflow.com/questions/3320417/… 上的正确答案。我喜欢它,谢谢!
  • @Alnitak 我对它投了赞成票并评论了人们应该看看你的答案,因为它更快更简单。再次感谢!
猜你喜欢
  • 1970-01-01
  • 2019-01-26
  • 1970-01-01
  • 2011-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-13
  • 2018-01-21
相关资源
最近更新 更多