Image gradient on HTML5 canvas

时光总嘲笑我的痴心妄想 提交于 2019-12-06 14:29:39

问题


I would like to obtain a radial gradient effect on an image (alpha = 1 in the middle and transparent on the edges).

Do you have any ideeas on how I could do that?


回答1:


If I'm not mistaking what you want to do is:

  1. Draw the image
  2. Draw a radial gradient over it, where the borders are transparent and the middle is opaque and using the globalCompositeOperation setting on the context to blend the transparency gradient with the image.

You can rather easily translate this into code: 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
};


来源:https://stackoverflow.com/questions/6424840/image-gradient-on-html5-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!