I know that I can clip a canvas by creating a path with getContext('2d')
and setting globalCompositeOperation
.
I've noticed that sometimes I'm able to clip a canvas with -webkit-clip-path
, or clip-path
on other browsers (I'm on Chrome), and sometimes I'm not able to:
Using this HTML:
<canvas width="300" height="60"></canvas>
and CSS:
canvas {
-webkit-clip-path: polygon(50% 33%, 75% 10%, 80% 80%, 60% 75%, 40% 60%, 20% 10%, 40% 20%, 50% 33%);
}
produces this:
Which appears to be correct.
However, I've noticed that if I change the height of the canvas, it fails to clip:
<canvas width="300" height="250"></canvas>
produces:
My assumption was that it has a problem clipping on floating points (where the percentages clip between pixels instead of on pixels), but changing from percents to pixel coordinates doesn't clip.
*Here are links to their jsfiddle pages respectively:
Does anyone know why one works but the other doesn't?
Is there a stable way to clip canvas elements with CSS, or do I need to use the canvas context methods?
The reason I ask is that I'd like to use less js where possible. I have a string of coordinates which I can easily put into css; whereas, to use the ctx.beginPath()...ctx.moveTo()...ctx.lineTo()...ctx.lineTo()...
method I'll need to do a for loop for the points.
Also, I'm very curious as to why the first example worked, if anyone can explain that. Thanks! :)