Reputation: 1195
The html5 canvas tag has the javascript getImageData() function associated to it, and its return value is a rectangle containing the enclosed pixels.
But instead of a rectangle, I need to get back from my original canvas a triangle shaped image, enclosed by the points I've choosen.
Does anybody know of a what to get a triangle shaped image from the html5 canvas?
Upvotes: 9
Views: 3704
Reputation: 16802
If it's for efficiency purposes, then no you can not get a non-rectangular shape using getImageData()
. However, if you want the functionality, then you could clip like so (JS Lint Example):
var img1 = new Image();
img1.onload = function(){
var w = img1.width
var h = img1.height
ctx.drawImage(img1,0,0);
// Create a circular clipping path
ctx.translate(w / 2, 1.5 * h);
ctx.beginPath();
ctx.arc(0,0,100,0,Math.PI*2,true);
ctx.clip();
ctx.drawImage(img1,-w / 2,-150);
}
img1.src = "foobar.jpg";
What you get is the original, then the clipped version. You can do this every time you load an image. Alternatively, you can create an image by creating a second canvas, drawing to it but with the clip. Essentially this creates a cached version of your image, it is still a rectangle, but the clip renders everything outside of the clip transparent (if you like I can provide an example of that too see here).
Upvotes: 8
Reputation: 25165
Note that all the images are rectangular. getImageData returns bitmap data, so it will be a 2x2 array of bytes. What you can do is draw a path with the points you want and clip the canvas content using it. It will be like a PNG image with transparent pixels as background.
Upvotes: 0
Reputation: 31854
I pretty much never work with image processing in any form, so cant suggest specifics, but you could probably just paint the unwanted portions transparent, then copy the rectangle.
maybe search for path, clipping region, fill
Upvotes: 0
Reputation: 63872
You can't.
Depending on what you're trying to do, instead just get the smallest rectangle that is the union of all the points and only use the imageData
of the pixels that you care about.
In other words, if your triangle has points at (50,50), (100, 100) and (0,100) then get a rectangle from (0,50) that is 100 wide with a height of 50. Then only use the imagedata of the pixels you care about.
If you literally want a triangle-shaped image, well, those don't exist.
Upvotes: 0