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 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100