javascript - HTML5 canvas 画布显示问题
ringa_lee
ringa_lee 2017-04-10 16:57:48
[JavaScript讨论组]
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <style type="text/css">
    </style>
</head>
<body>
    <canvas id="myCanvas" width="300" height="200" style="border:1px solid blue;"></canvas>
    <p id="p1"></p>
    <script type="text/javascript">
        var canv = document.getElementById('myCanvas');
        var context = canv.getContext('2d');
        context.fillStyle = "#ff0000";
        context.fillRect(0, 0, 100, 100);
    </script>
</body>
</html>

上面代码显示正常效果如下:

但是如果把 canvas的样式放在head中,结果运行效果如下图所示(画布并不是100*100的尺寸,这就是我疑问的地方),

后者效果的代码如下:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <style type="text/css">
        #myCanvas{
            width:300px;
            height:200px;
            border:1px solid blue;
        }
    </style>

</head>
<body>
    <canvas id="myCanvas"></canvas>
    <p id="p1"></p>
    <script type="text/javascript">
        var canv = document.getElementById('myCanvas');
        var context = canv.getContext('2d');
        context.fillStyle = "#ff0000";
        context.fillRect(0, 0, 100, 100);
    </script>
</body>
</html>
ringa_lee
ringa_lee

ringa_lee

全部回复(3)
ringa_lee

Indeed, the <canvas> element has only two attributes, width and height. These are both optional and can also be set using DOM properties. When no width and height attributes are specified, the canvas will initially be 300 pixels wide and 150 pixels high. The element can be sized arbitrarily by CSS, but during rendering the image is scaled to fit its layout size: if the CSS sizing doesn't respect the ratio of the initial canvas, it will appear distorted.

canvas元素只有2个DOM属性(除了全局的属性外),当没有显时的指定这2个属性时,系统会提供300宽,150高这2个值给canvas元素。你也可以通过CSS来指定这2个值,但是当CSS指定的宽高比和初始的宽高比不同时,canvas中的图像将会出现变形,按CSS中指定的比例进行缩放

问题的中的第1段代码指定了width和height,那么图像在这个宽高的画布上进行绘制;
第2端代码在CSS中指定,但是在canvas的DOM元素上没有指定宽高,那么按默认的300/150来先设定画布大小,CSS中重新指定了300/200,那么在宽度上没有变化,高度上缩放了原来的20/15约等于1.33倍,那么看到的最终图形效果在高度上为133。

同时如果你通过JS来重新设置Canvas的width和height属性值(不是通过CSS改变),那么真个画布中的图像将被清除掉

迷茫

可以看看这篇问题,具体的原因是不是因为拉伸了,我并不知道

canvas画布的宽高应写在<canvas>标签里

大家讲道理

canvas.width = '';
canvas.height = '';
最好这样写,不然会变形,好像是跟分辨率有关。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号