0

私は HTML5 をまったく初めて使用し、ここ数日間 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>
4

1 に答える 1

0

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'); 
于 2012-06-09T09:47:14.827 に答える