Quantcast
Viewing all articles
Browse latest Browse all 15

Tutorial – Fullscreen Button With Canvas

So lets start with defining the markup:

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<h3>Canvas Fullscreen Button</h3>
<canvas id="output2" width="300" height="300"></canvas>
  

</body>
</html>

We don’t need jQuery so you can get rid of that if you want.

Next, we open a script tag and we select the canvas element and it’s appropriate context.

var c=document.getElementById("output2");
var ctx=c.getContext("2d");

We calculate the dimensions of the canvas element and we will draw the button relative to the that size so that if you want later to change the size you won’t swear your past self for not implementing this.

var ctx_w = c.width;
var ctx_h = c.height;
var ctx_pw = ctx_w/100;
var ctx_ph = ctx_w/100;

We set the border width AND draw the square on the center.

var borderw = 30;
ctx.fillStyle="#FF0000";
ctx.fillRect(25*ctx_pw,25*ctx_ph,50*ctx_pw,50*ctx_ph);

Finally we draw the triangles in the corners and we are done.

  ctx.beginPath();
  ctx.moveTo(0*ctx_pw,0*ctx_ph);
  ctx.lineTo(0*ctx_pw,borderw*ctx_ph);
  ctx.lineTo(borderw*ctx_pw,0*ctx_ph);
  ctx.fill();
  ctx.moveTo(0*ctx_pw,100*ctx_ph);
  ctx.lineTo(0*ctx_pw,(100-borderw)*ctx_ph);
  ctx.lineTo(borderw*ctx_pw,100*ctx_ph);
  ctx.fill();
  ctx.moveTo((100)*ctx_pw,(100)*ctx_ph);
  ctx.lineTo((100-borderw)*ctx_pw,(100)*ctx_ph);
  ctx.lineTo((100)*ctx_pw,(100-borderw)*ctx_ph);
  ctx.fill();
  ctx.moveTo((100)*ctx_pw,(0)*ctx_ph);
  ctx.lineTo((100-borderw)*ctx_pw,(0)*ctx_ph);
  ctx.lineTo((100)*ctx_pw,(borderw)*ctx_ph);

Viewing all articles
Browse latest Browse all 15

Trending Articles