I'm trying to make a tag like icon in canvas, but having a hard time doing the punch hole in the middle with no lines.
If possible, would like to make it like in the image, since here I tried with just basics shapes.
Image Example:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.rect(100, 30, 150, 100);
ctx.lineWidth = 1;
ctx.stroke();
ctx.beginPath();
ctx.translate(c.width/2,c.height/2);
ctx.moveTo(0,0);
ctx.lineTo(0,0-100);
ctx.rotate(Math.PI / 3);
ctx.lineTo(0,0-100);
ctx.closePath();
ctx.stroke();
<canvas id="myCanvas" width="500" height="260" style="border:1px solid #d3d3d3;">
CodePudding user response:
You had a good start, we just needed to draw the circle with the ctx.arc(
and use the globalCompositeOperation
to cut out the hole to match your image.
On my example below I created a function that does the drawing of the tag, that way we can reuse to draw multiple tags
Improvements you could do later, maybe pass more parameters to have more control over how big is that triangle also the radius of the circle, and of course add color that is all up to you.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.lineWidth = 1;
function drawTag(x, y, w, h) {
ctx.beginPath();
ctx.rect(x, y, w, h);
ctx.moveTo(x w, y);
ctx.lineTo(x w w / 2, y h / 2);
ctx.lineTo(x w, y h);
ctx.fill();
ctx.beginPath();
ctx.globalCompositeOperation = 'destination-out';
ctx.arc(x w w / 8, y h / 2, h / 8, 0, 8, false)
ctx.fill();
ctx.globalCompositeOperation = 'source-over';
}
drawTag(10, 10, 75, 50)
ctx.translate(140,50);
ctx.rotate(1);
drawTag(0, 0, 60, 40)
ctx.translate(40,60);
ctx.rotate(2);
drawTag(0, 0, 50, 30)
<canvas id="myCanvas" style="border:1px solid #d3d3d3;">