前言

大家好,想必各位猿们都知道canvas的width和height属性在w3c标准中规定要写在行内,作为标签属性而不是行内样式,但是究竟是为什么呢?我为什么要写行内呢?写样式里不可以吗?有什么特殊含义吗?不就是宽度和高度吗?等等诸多疑问却很少有人去了解,在这里且听笔者一一道来。
当时看到这个规定时,笔者亦不以为然,之后在一段时间使用中,有时候写行内,有时候写样式中,感觉跟div的宽高属性没什么区别,不过最近在写设置游戏分辨率功能时,有更深入的了解,才恍然大悟,原来是有原因的,width和height属性作为标签属性写在行内代表的是画布的分辨率(resolution),而写在样式里代表的是画布的大小(size)。废话少说,请看代码:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        *{
            margin:0;padding:0;
        }
        body{
            width:100%;height:100%;background:black;
        }
        canvas{
            width:800px;height:480px;outline:1px solid pink;position:absolute;
            left:0;top:0;right:0;bottom:0;margin:auto;
        }
    </style>
</head>
<body>
    <button>240x120</button>
    <button>320x240</button>
    <button>480x320</button>
    <button>640x420</button>
    <button>800x480</button>
    <canvas id="canvasId" width="480" height="320">
        Your browser does not support the canvas element.
    </canvas>
    <script>
        var canvas = document.getElementById('canvasId');
        var context = canvas.getContext('2d');
        var btns = document.getElementsByTagName('button');
        var resolution = [
            [240, 120],
            [320, 240],
            [480, 320],
            [640, 420],
            [800, 480]
        ];
        //canvas分辨率
        var resolutionW = canvas.getAttribute('width');
        var resolutionH = canvas.getAttribute('height');
        //canvas大小
        var sizeW = canvas.offsetWidth;
        var sizeH = canvas.offsetHeight;
        console.log(resolutionW);
        console.log(resolutionH);
        console.log(sizeW);
        console.log(sizeH);
        var img = new Image();
        img.src = "http://img5.niutuku.com/phone/1301/0920/0920-niutuku.com-483082.jpg"; //这张图片像素为800x480
        img.onload = function() {
            draw(3);
            for (var i = 0; i < btns.length; i++) {
                (function(i) {
                    btns[i].onclick = function() {
                        draw(i);
                    }
                })(i);
            }
        }

        function draw(i) {
            canvas.setAttribute('width', resolution[i][0]);
            canvas.setAttribute('height', resolution[i][1]);
            context.clearRect(0, 0, sizeW, sizeH);
            context.drawImage(img, 0, 0, sizeW, sizeH, 0, 0, resolution[i][0], resolution[i][1]);
        }
    </script>
</body>
</html>

大家运行一下,就可以发现,改变了canvas标签中的width和height属性,发现其大小没有改变,而里边图片的清晰度发生了变化,怎么样,是不是恍然大悟呢?


本文转载:CSDN博客