首页 > 解决方案 > 如何在js中找到画布的中心

问题描述

我有canvas。我有一个ctx. 我希望在 的中心ctx绘制,但是canvas

canvas.height/2
canvas.width/2

不工作

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

另外,我需要证明它在我接受之前有效

标签: javascripthtmlhtml5-canvas

解决方案


看看下面的代码。

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>

它可以完美地在画布的中心绘制一个矩形。


推荐阅读