-1

I wanted to make a close button using rectangle in HTML5 canvas, here is the code for the box:

function close_button(ctx)
{
    ctx.fillStyle = "red";
    ctx.fillRect(500, 30, 30, 30);
}   

my problem is I don't know how to make cross in middle of the red box,can someone help me?

Anis D
  • 761
  • 11
  • 25

1 Answers1

2

Try this:

function close_button(x,y,side){

  ctx.fillStyle="red";
  ctx.fillRect(x, y, side, side);

  var shift = side/10;

  ctx.beginPath();
  ctx.moveTo(x + shift, y + shift);
  ctx.lineTo(x + side - shift, y + side - shift);
  ctx.moveTo(x + side - shift, y + shift);
  ctx.lineTo(x + shift, y + side - shift);
  ctx.strokeStyle = '#FFFFFF';
  ctx.stroke();
}

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
c.width = 300;
c.height = 300;

close_button(10, 10, 20);
canvas {
  width:300px;
  height:300px;
  background-color:#ffffff;
}
<canvas id="myCanvas"></canvas>

JSFiddle example

Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Baro
  • 5,300
  • 2
  • 17
  • 39
  • and how to bind javaScript event on close button? – Devang Hingu Jul 19 '21 at 09:19
  • @DevangHingu You can add event to whole canvas. SVG is a better alternative if you want interactive elements. Anyway, check this SO answer, contains some alternative too [link](https://stackoverflow.com/questions/9880279/how-do-i-add-a-simple-onclick-event-handler-to-a-canvas-element) – Baro Jul 19 '21 at 09:33
  • Actually i was looking a way to add close button near specific line in canvas so i can remove that lines – Devang Hingu Jul 19 '21 at 10:07