Shanky
Shanky

Reputation: 203

How can i draw a Square in HTML5 Canvas at run time?

I am working on a HTML5 Project.There is a drawing graphics API to draw Rectangle (fillRectStrokeRect).But how can i draw a SQUARE. I have tried the following way to draw it CODE

getMouse(e);
x2=mx; y2=my;
var width=endX-startX;
var height=endY-startY;

annCanvasContext.beginPath();
annCanvasContext.lineWidth=borderWidth;
var centerX=width/2;
var centerY=width/2;
var radius=width/2;
annCanvasContext.arc(centerX+5, centerY+5, radius, 0, 2 * Math.PI, false);
annCanvasContext.stroke();

Upvotes: 0

Views: 2532

Answers (1)

Some Guy
Some Guy

Reputation: 16210

Use fillRect or strokeRect with the width and height being equal.

var x = 0, y = 0,
    side = 10;

ctx.fillRect(x, y, side, side);

Demo

As you say in the comments, if you want to fit the largest square in a circle, it's more Math related than about code. I'll trying explaining it to you, but you'll probably find better, more visual explanations elsewhere on the Internet.

Draw the diameter of the circle in a way that it divides your square into two equal parts. Now one part is a right angled triangle, which has two of its sides equal. We know the diameter. Using the Pythogorean theorem, you get this equation: side^2 + side^2 = diameter^2.

Let's find the side now.

2(side^2) = diameter^2
side^2 = (diameter^2)/2
side = Math.sqrt( (diameter^2)/2 )

Now, to turn this into code.

var ctx = document.getElementById('canvas').getContext('2d'),
    radius = 20;

ctx.canvas.addEventListener('click', function (e){
    ctx.fillStyle = 'black';
    ctx.arc(e.pageX, e.pageY, radius, 0, Math.PI*2, false);
    ctx.fill();
    ctx.beginPath();
    ctx.fillStyle = 'red';
    var diameter = radius * 2;
    var side = Math.sqrt( (diameter * diameter)/2 );
    ctx.fillRect(e.pageX - side/2, e.pageY - side/2, side, side);
    ctx.closePath();
}, false);

This would draw a square inside a circle wherever you click on the canvas.

Demo

Upvotes: 2

Related Questions