Нарисуйте внешнюю фигуру с помощью контура, также известного как moveTo
, lineTo
и т. Д. Затем нарисуйте отрицательную фигуру внутри этой формы, но в противоположном направлении по часовой стрелке / против часовой стрелки.Затем назовите fill()
.
Вот пример рисования круга с круглым отверстием.
<html><head></head><body>
<canvas id="canvas" width=600 height=600></canvas>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var width = canvas.width, height = canvas.height;
var context = canvas.getContext("2d");
// draw a diagonal line just to demonstrate the transparency later
context.beginPath();
context.moveTo(width/2 - height/2, 0);
context.lineTo(width/2 + height/2, height);
context.lineWidth = 3;
context.strokeStyle = "#0f0";
context.stroke();
// draw a circle with a hole in it
context.beginPath();
context.arc(width/2, height/2, height*3/8, 0, 2*Math.PI);
context.arc(width/2, height/2, height*1/8, 0, 2*Math.PI, true);
context.fillStyle = "#555";
context.fill();
</script>
</body>
</html>