dsfadsa08911 2013-03-11 18:04
浏览 88
已采纳

HTML5画布重新着色图像*之前*渲染

I have an image which is essentially a star-burst effect. The color of the star-burst is white, and the background is transparent (PNG w/ Alpha). I randomly generate these star-bursts onto an HTML5 canvas at random locations, and at the same time, generate random Hue, Saturation, and Light (HSL) values. These could be RGB values, if this simplifies things.

The goal is to re-colorize the PNG for display on the HTML5 canvas based on the randomly generated HLS values before rendering it to the canvas.

I've read some other posts on StackOverflow and other sites, but the only solutions I've seen involve rendering it to the canvas, grabbing the coordinates for where the image is displaying, and modify the color on a pixel-by-pixel basis. In theory this could work, however some of the images may overlap slightly. Also if there is a background already present, then from what I understand, the background's color would also be modified which isn't much of a solutions for me either.

If this is out of the realm of what Canvases are capable of, as a fallback I suppose I would be okay with having images dynamically re-colored via PHP using GD2 or Imagick, or via the command-line via Gimp, ImageMagick or some other image library...

Thanks much!

-- OUTCOME --

Special thanks to @jing3142 for initial suggestion of off-screen canvas rendering, and @Jarrod for providing the vital piece I was missing: globalCompositeOperation = "source-in"

Here is a working implementation of the concept: http://jsfiddle.net/fwtW2/2/

Works in:

  • Chrome
  • Firefox
  • IE 9 (haven't tested other versions)
  • 写回答

3条回答 默认 最新

  • douchaqi3369 2013-03-12 20:33
    关注

    I'm pretty sure you can just use the source-in globalCompositeOperation opertaion? No need to get all hardcore and crazy with vector images.

    This code is where the magic happens:

    var color = 'red';
    ctx.fillStyle = color;
    ctx.globalCompositeOperation = "source-in";
    

    But yOu'd need to re-draw this to an offscreen canvas: You can do that like so

    createBuffer = function(sizeW, sizeH)
    {
        buffer = document.createElement('buffer');
        bufferCtx = buffer.getContext('2d');
    
        buffer.width = sizeW;
        buffer.height = sizeH;
    

    }

    then just draw your image to the offscreen canvas and apply the global composition.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图