【问题标题】:Positioning an HTML5 Canvas Element定位 HTML5 画布元素
【发布时间】:2012-06-13 03:42:45
【问题描述】:

我对 HTML5 完全陌生,过去几天一直在阅读它,主要是因为我想创建一个旋转图像以放入 <div>。我找到了一个完全符合我要求的代码,但它把画布扔到了我页面的左下角(我不知道为什么,但我认为它与下面代码的第一行有关)。我不知道如何使代码适应一个元素,以便我可以把它放在我想要的地方。通过查看其他人的脚本并尝试模仿他们,我知道你应该做这种事情来保持画布“<canvas width="100" height="100" id="pageCanvas"></canvas>”,但我不知道如何命名下面的代码以便做那。我非常感谢任何人可以为我提供的任何帮助 - 非常感谢您的阅读! :)

<script>

    window.addEventListener("load", init); 

    var counter = 0,
        logoImage = new Image(),
        TO_RADIANS = Math.PI/180; 
    logoImage.src = 'IMG URL';
    var canvas = document.createElement('canvas'); 
    canvas.width = 100; 
    canvas.height = 100; 
    var context = canvas.getContext('2d'); 
    document.body.appendChild(canvas); 

    function init(){
        setInterval(loop, 1000/30); 

    }

    function loop() { 
        context.clearRect(0,0,canvas.width, canvas.height); 
        drawRotatedImage(logoImage,100,100,counter); 
        drawRotatedImage(logoImage,300,100,counter+90); 
        drawRotatedImage(logoImage,500,100,counter+180); 
        counter+=2; 

    }


    function drawRotatedImage(image, x, y, angle) { 

        // save the current co-ordinate system 
        // before we screw with it
        context.save(); 

        // move to the middle of where we want to draw our image
        context.translate(x, y);

        // rotate around that point, converting our 
        // angle from degrees to radians 
        context.rotate(angle * TO_RADIANS);

        // draw it up and to the left by half the width
        // and height of the image 
        context.drawImage(image, -(image.width/2), -(image.height/2));

        // and restore the co-ords to how they were when we began
        context.restore(); 
    }
    </script>

【问题讨论】:

    标签: image html canvas rotation


    【解决方案1】:

    在您的 HTML 代码中创建一个画布元素,以便您可以将其准确放置在您想要的位置(使用 html + css):

    <canvas id='canvas' height='100' width='100'> Your browser does not support HTML5 canvas </canvas>
    

    并替换此 javascript 代码:

    var canvas = document.createElement('canvas'); 
    canvas.width = 100; 
    canvas.height = 100; 
    var context = canvas.getContext('2d'); 
    document.body.appendChild(canvas); 
    

    这个:

    var canvas = document.getElementById('canvas'); 
    var context = canvas.getContext('2d'); 
    

    【讨论】:

    • 非常感谢! :) 工作完美!
    猜你喜欢
    • 2011-03-01
    • 2012-06-30
    • 2020-01-08
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多