簡體   English   中英

使用JavaScript調整HTML畫布的大小

[英]Resizing html canvas using javascript

我正在嘗試平滑調整html5 canvas元素的大小。 我整理了一些代碼,我認為以下應該可行:

<body>
    <header id='myheader' height='200'>
        <canvas id='mycanvas' width='200' height='200'></canvas>

        <script>

        var mycanvas = document.getElementById('mycanvas');
        var context = mycanvas.getContext('2d');
        var centerX = mycanvas.width / 2;
        var centerY = mycanvas.height / 2;
        var radius = 70;

        context.beginPath();
        context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
        context.fillStyle = 'blue';
        context.fill();
        context.lineWidth = 5;
        context.strokeStyle = '#003300';
        context.stroke();

        var animate = function(prop, val, duration) {
            var start = new Date().getTime();
            var end = start + duration;
            var current = mycanvas[prop];
            var distance = val - current;
            var step = function() {
                var timestamp = new Date().getTime();
                var progress = Math.min((duration - (end - timestamp)) / duration, 1);
                mycanvas[prop] = current + (distance * progress);
                if (progress < 1) requestAnimationFrame(step);
            };
            return step();
        };

        animate('mycanvas.height', 10, 1000);

        </script>
    </header>       
</body>

...但是顯然不是! 我要尋找的結果是縮小到僅顯示圓圈中間部分的畫布(稍后會添加比圓圈更有趣的東西)。 有什么明顯的我想念的東西嗎?還是我做錯了呢? 最終,我想同時調整畫布和頁眉的大小,因此,調整畫布的大小才能正常工作是第1階段。感謝任何幫助...

(編輯:實際上,我最終希望對畫布和標頭同時調整大小以響應滾動事件-我認為這意味着避免使用CSS解決方案-但我想首先使這一點起作用!)

以下是對腳本的一些更改,我相信這些更改可以滿足您的要求:

    var mycanvas = document.getElementById('mycanvas');
    var context = mycanvas.getContext('2d');
    var radius = 70;

    function draw() {
        var centerX = mycanvas.width / 2;
        var centerY = mycanvas.height / 2;

        context.beginPath();
        context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
        context.fillStyle = 'blue';
        context.fill();
        context.lineWidth = 5;
        context.strokeStyle = '#003300';
        context.stroke();
    }

    var animate = function(target, prop, val, duration, action) {
        var start = new Date().getTime();
        var end = start + duration;
        var current = target[prop];
        var distance = val - current;
        var step = function() {
            var timestamp = new Date().getTime();
            var progress = Math.min((duration - (end - timestamp)) / duration, 1);
            target[prop] = current + (distance * progress);
            action();
            if (progress < 1) requestAnimationFrame(step);
        };
        return step();
    };

    animate(mycanvas, 'height', 10, 1000, draw);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM