问题
I'm using an HTML5 canvas to create a series of trees and their corresponding shadows. I want each shadow to be based on the position of a light source. I can draw each tree and it's shadow as well as skew all the shadows at once, but trying to skew each shadow individually eludes me. Here's my code:
var ctx = cvs[0].getContext('2d');
ctx.save();
//skew the canvas
ctx.transform(1,0,0.3,-1,0,0);
ctx.drawImage(tree1,74,-117,20,40);
ctx.drawImage(tree1,126,-125,20,40);
var imgd = ctx.getImageData(0, 0, 500, 300);
var pix = imgd.data;
//convert the drawn trees to shadows
for (var i = 0, n = pix.length; i < n; i += 4) {
pix[i ] = 0; // red
pix[i+1] = 0; // green
pix[i+2] = 0; // blue
// alpha
}
ctx.putImageData(imgd, 0, 0);
//remove the skewing
ctx.restore();
//draw full color trees
ctx.drawImage(tree1,50,40,20,40);
ctx.drawImage(tree1,100,50,20,40);
Is there a way to skew the images as I draw them using drawImage? Thanks in advance!
回答1:
There are two things you have to understand here.
When you apply a transformation to the context you do not apply it to anything already drawn. You only apply the transformation to things that are about to be drawn.
In other words, it is always the case that you skew images as you draw them using drawImage! That's the only way its done.
There's an exception to this rule that you should keep in mind since you're using imageData: Putting imageData onto the canvas is pixel perfect and ignores any transformation matrix.
So if you want a different skew for each shadow all you have to do is transform the context, draw thing A, then restore and transform the context in some other way and draw thing B.
Here's an example using your code:
http://jsfiddle.net/QfrVB/
On a side note, you really don't have to use imageData here at all. Using it is a really slow operation (important if you're making an animated app like a game) and you should avoid it if you can.
Instead of doing this:
var imgd = ctx.getImageData(0, 0, 500, 300);
var pix = imgd.data;
//convert the drawn trees to shadows
for (var i = 0, n = pix.length; i < n; i += 4) {
pix[i ] = 0; // red
pix[i+1] = 0; // green
pix[i+2] = 0; // blue
// alpha
}
ctx.putImageData(imgd, 0, 0);
You can just do this:
ctx.globalCompositeOperation = 'source-atop';
ctx.fillStyle = 'black';
ctx.fillRect(0,0,500,300);
ctx.globalCompositeOperation = 'source-over'; // back to normal
What that code does is draw black over all pixels that currently exist on the canvas. Since you draw all shadows first you can black all of them out with one call to fillRect this way.
See that live here: http://jsfiddle.net/QfrVB/2/
来源:https://stackoverflow.com/questions/9253091/skewing-images-individually-using-canvas