Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get a non-rectangular shape using getImageData()?

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?

like image 794
Draconar Avatar asked Dec 22 '11 21:12

Draconar


People also ask

What does getImageData return?

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.

What is ImageData?

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() .

How do I get data from canvas?

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.


1 Answers

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).

like image 79
puk Avatar answered Sep 19 '22 00:09

puk