如何在画布上居中放置矩形 [英] How do I center a rectangle on a canvas

查看:61
本文介绍了如何在画布上居中放置矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个最模糊的想法,为什么这个代码块不会使矩形在画布上居中.甚至最终超出了范围.

I have the vaguest idea why this block of code won't center the rectangle on the canvas. It even ends up being drawn out of bounds.

请帮助?

 document.addEventListener('DOMContentLoaded', drawIllustrations);                                                                   

 function drawIllustrations(e) {                                                                                                     

   var fixedBody = document.getElementById('FixedBody'),                                                                             
       contextOne = fixedBody.getContext('2d'),                                                                                      
       centerX = fixedBody.offsetWidth * 0.5;                                                                                        

   contextOne.fillStyle = "#BFFF00";                                                                                                 
   contextOne.fillRect(centerX - 100,0,200,fixedBody.offsetHeight);                                                                  

 } 

推荐答案

要将矩形在画布上居中,您需要知道画布的宽度.然后,这很容易.矩形的 x canvasWidth/2-矩形宽度/2

To center the rectangle on the canvas, you'll need to know the width of the canvas. Then it's pretty easy. The x of your rect would be canvasWidth/2 - rectangleWidth/2

所以在您的情况下:

contextOne.fillRect(fixedBody.width/2-(200/2),0、200,fixedBody.height);

这篇关于如何在画布上居中放置矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆