我的问题是,使用drawImage方法绘制图像的最佳方式是什么?目标用途是高级的二维粒子效应(游戏开发),其中粒子随着时间的推移而改变颜色等等。我不是问如何使整个画布变暗,而只是画出我目前的图像。
我已经得出结论,globalAlpha参数会影响当前绘制的图像。
//works with drawImage() canvas2d.globalAlpha = 0.5;
但是,如何使用任意颜色值对每个图像进行着色?如果有某种globalFillStyle或globalColor或某种事情,这将是非常棒的…
编辑:
以下是我正在使用的应用程序的屏幕截图:
http://twitpic.com/1j2aeg/full
alt text http://web20.twitpic.com/img/92485672-1d59e2f85d099210d4dafb5211bf770f.4bd804ef-scaled.png
解决方法
你有合成操作,其中之一是目的地。如果使用’context.globalCompositeOperation =“destination-atop”’将图像合成为纯色,则它将具有前景图像的alpha和背景图像的颜色。我用这个来完成一个完全有色的副本的图像,然后在原始的顶部绘制完全有色的副本,其透明度等于我想要的色彩。
以下是完整的代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>HTML5 Canvas Test</title> <script type="text/javascript"> var x; //drawing context var width; var height; var fg; var buffer window.onload = function() { var drawingCanvas = document.getElementById('myDrawing'); // Check the element is in the DOM and the browser supports canvas if(drawingCanvas && drawingCanvas.getContext) { // Initaliase a 2-dimensional drawing context x = drawingCanvas.getContext('2d'); width = x.canvas.width; height = x.canvas.height; // grey Box grid for transparency testing x.fillStyle = '#666666'; x.fillRect(0,width,height); x.fillStyle = '#AAAAAA'; var i,j; for (i=0; i<100; i++){ for (j=0; j<100; j++){ if ((i+j)%2==0){ x.fillRect(20*i,20*j,20,20); } } } fg = new Image(); fg.src = 'http://uncc.ath.cx/LayerCake/images/16/3.png'; // create offscreen buffer,buffer = document.createElement('canvas'); buffer.width = fg.width; buffer.height = fg.height; bx = buffer.getContext('2d'); // fill offscreen buffer with the tint color bx.fillStyle = '#FF0000' bx.fillRect(0,buffer.width,buffer.height); // destination atop makes a result with an alpha channel identical to fg,but with all pixels retaining their original color *as far as I can tell* bx.globalCompositeOperation = "destination-atop"; bx.drawImage(fg,0); // to tint the image,draw it first x.drawImage(fg,0); //then set the global alpha to the amound that you want to tint it,and draw the buffer directly on top of it. x.globalAlpha = 0.5; x.drawImage(buffer,0); } } </script> </head> </body> <canvas id="myDrawing" width="770" height="400"> <p>Your browser doesn't support canvas.</p> </canvas> </body> </html>