How to get non-rectangular shape using getImageData ()?

The html5 canvas tag has a javascript getImageData () function associated with it, and its return value is a rectangle containing nested pixels.

But instead of the rectangle, I need to return from my original canvas an image in the shape of a triangle, enclosed in the items that I selected.

Does anyone know what to get a triangle shaped image from html5 canvas?

+6
source share
4 answers

If this is for efficiency, then no you cannot get a non-rectangular shape using getImageData() . However, if you want to use the functionality, you can clip like this ( Example JS Lint ):

 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, and then the cropped version. You can do this every time you upload an image. In addition, you can create an image by creating a second canvas, drawing it, but with a clip. In essence, this creates a cached version of your image, it is still a rectangle, but the clip makes everything outside the clip transparent ( if you like, I can give an example of this, too, see here ).

+5
source

You can not.

Depending on what you are trying to do, instead, just get the smallest rectangle, which is the union of all the points, and use only imageData for the pixels you are interested in.

In other words, if your triangle has points at (50,50), (100, 100) and (0,100), then you will get a rectangle from (0.50), which is 100 wide with a height of 50. Then just use imagedata pixels, about which you care.

If you literally want a triangle-shaped image, well, those don't exist.

0
source

I almost never work with image processing in any form, so I can’t offer features, but you could just draw the unwanted parts transparent, and then copy the rectangle.

possible search for path, clipping area, fill

0
source

Please note that all images are rectangular. getImageData returns bitmap data, so it will be an array of 2x2 bytes. What you can do is draw a path with the desired points and crop the contents of the canvas using it. It will look like a PNG image with transparent pixels as the background.

0
source

Source: https://habr.com/ru/post/904347/


All Articles