HTML Canvas:width/height属性和width/height样式之间的区别 [英] Html Canvas : difference between width/height attribute and width/height style

查看:71
本文介绍了HTML Canvas:width/height属性和width/height样式之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在调整画布大小上看到了各种答案,但无法理解我面临的问题.以下是在我的Web应用程序上呈现的canvas元素.

I have seen various answers on canvas resize but could not understand the problem I am facing. Following is the canvas element rendered on my web app.

Before Rendering: 

    <canvas id="g_5" resize></canvas>

After Rendering:

     <canvas id="g_5"  resize width="1076" height="306" style="-webkit-user-select: none; touch-action: none; -webkit-user-drag: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); width: 1148.38px; height: 300px;"></canvas>  

我正在如下设置画布的高度和宽度:

I am setting height and width of canvas as follows:

        var canvas = document.getElementById(canvasId);
        var context = canvas.getContext('2d');
        var width = <someWidth>;  //=1076 in this case
        var height = <someHeight>; //=306 in this case
        canvas.width = width;
        canvas.height = height;

完成此操作后,样式中的width/height会取代属性width/height,因此canvas会使用样式的height/width.

After doing this, width/height in style supersedes the attribute width/height and hence canvas uses style's height/width.

我的问题是:

  1. 为什么宽度/高度有两种不同?
  2. 如何将它们设置为具有相同的值
  3. 如果从画布元素中删除 resize 属性,则画布大小将保持默认大小.
  1. Why there are two different width/height?
  2. How to set them to have same value
  3. If I remove resize attribute from canvas element, canvas size stays to default size.

推荐答案

  1. 首先应用在html属性中设置宽度/高度,直到加载CSS.
  2. 在加载css后,width/height属性将被忽略,并使用其样式定义.
  3. 使用javascript调整大小代码后,您将在该事件中调整画布的大小.

这篇关于HTML Canvas:width/height属性和width/height样式之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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