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?
The getImageData() method returns an ImageData object that copies the pixel data for the specified rectangle on a canvas. Note: The ImageData object is not a picture, it specifies a part (rectangle) on the canvas, and holds information of every pixel inside that rectangle.
The ImageData interface represents the underlying pixel data of an area of a <canvas> element. It is created using the ImageData() constructor or creator methods on the CanvasRenderingContext2D object associated with a canvas: createImageData() and getImageData() .
To get the image data for each pixel of a rectangular area on the canvas, we can get the image data object with the getImageData() method of the canvas context and then access the pixel data from the data property. Each pixel in the image data contains four components, a red, green, blue, and alpha component.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With