画布高度错误 [英] Getting wrong canvas height

查看:111
本文介绍了画布高度错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了错误的画布高度。这里有什么问题?
我做了一个小提琴: http://jsfiddle.net/hbcz6/

I get a wrong canvas height. Whats wrong here? I made a fiddle: http://jsfiddle.net/hbcz6/

HTML

<div id="app">
    <div id="percent" class="animated"></div>
    <canvas></canvas>
</div>

Javascript

var canvas = document.getElementsByTagName("canvas")[0];

var context = canvas.getContext('2d');
var x = canvas.width / 2;
console.log("canvas X: ", x);
var y = canvas.height / 2;
console.log("canvas y: ", y);

请查看您的控制台。

推荐答案

由于您不设置画布元素的大小,其位图将默认为300 x 150像素。如果你使用CSS规则,那么元素将被拉伸,但位图将保持相同的大小只是缩放到适合元素的大小(就像一个图像)。

As you are not setting the size of the canvas element its bitmap will default to 300 x 150 pixels. If you use CSS rules then the element will be stretched but the bitmap will, stay at the same size just scaled to fit the size of the element (just like an image would).

下面是如何在父元素中正确设置其大小来动态地适应canvas元素:

Here is how to dynamically fit a canvas element inside a parent element settings its size properly:

首先,删除宽度和高度从CSS规则:

First, remove the width and height from the CSS rule:

#app canvas {
    border:2px solid red;
    }

然后使用getComputedStyle以像素为单位获取父元素的维度:

Then use getComputedStyle to get the parent element's dimension in pixels:

var cs = getComputedStyle(app),
    width = parseInt(cs.getPropertyValue('width'), 10);
    height = parseInt(cs.getPropertyValue('height'), 10);

parseInt $ c> px - 现在只需使用canvas元素:

The parseInt will remove the px at the end - now simply use those for the canvas element:

canvas.width = width;
canvas.height = height;

工作小提琴

Working fiddle here

这篇关于画布高度错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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