开发者

How to set a custom clipping zone for HTML5 Canvas?

I need to draw on a rectangle minus a circle. If the circle clipping is not possible, a polygonal clipping zone could be enough for my ne开发者_开发知识库ed.

How do I set a custom clipping zone for HTML5 Canvas?


You should read Compositing in the Canvas tutorial, it explains how you draw a rectangle minus a circle and similar figures.

I think you are looking for destination-out:

How to set a custom clipping zone for HTML5 Canvas?

<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function() {
    var ctx = document.getElementById('canvas').getContext('2d');
    ctx.fillStyle = "#09f";
    ctx.fillRect(15,15,70,70);

    ctx.globalCompositeOperation = 'destination-out';

    ctx.fillStyle = "#f30";
    ctx.beginPath();
    ctx.arc(75,75,35,0,Math.PI*2,true);
    ctx.fill();
}
</script>
</head>
<body>
<canvas id="canvas" width="400" height="300"/>
</body>
</html>

See it in action on jsFiddle.


Also you can use "clip" and than - "clear". Something like that:

drawRectangle(ctx);
walkCirclePath(ctx);
ctx.clip();
ctx.clear();

But antialiasing dont work in such way;


Well. It was hard.

The best solution I found to draw every where except in a circle is

c.save();
c.beginPath();
c.moveTo(0, 0);
c.lineTo(x, 0);
c.arc(x, y, 75, - Math.PI / 2, Math.PI * 2 - Math.PI / 2, 1);
c.lineTo(x, 0);
c.lineTo(1000, 0);
c.lineTo(1000, 500);
c.lineTo(0, 500);
c.clip();
c.drawImage(window.tBitmap[0], x - 100, y - 100);
c.restore();

I can't believe taht there is not a better solution. But it's works for my need.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜