Spam  Account
Spam Account

Reputation: 3

How can I find the center of a canvas in js

I have canvas. I have a ctx. I want the ctx to draw in the center of the canvas, however

canvas.height/2
canvas.width/2

does not work

http://jsfiddle.net/3hnbarcg/3/

Also, I need proof It works before I can accept

Upvotes: 0

Views: 4425

Answers (1)

Inus Saha
Inus Saha

Reputation: 1928

Have a look at following code.

var centerPointWidth = 10;
var centerPointHeight = 10;
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");

ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#000000";
ctx.fillRect((canvas.width / 2) - (centerPointWidth / 2), (canvas.height / 2) - (centerPointHeight / 2), centerPointWidth, centerPointHeight);
<canvas id="c"></canvas>

It works perfectly to draw a rectangle at the center of the canvas.

Upvotes: 5

Related Questions