简体   繁体   中英

Moving and rotating with HTML5

What needs to be done: The pink object should move from the left to the right (by itself). And then when it's 5px from the edge it should rotate 90 degrees.

Does anyone know how to do this?

I haven't been learning javascript for a long time, and it's the first time I'm creating something using HTML5. So it's all new. I really hope you can help me understand the code better and how I can make it move and rotate.

    <!DOCTYPE html>    
    <html>
    <head>
    <script>
    var canvas, ctx;    
    window.onload = function draw() {
    canvas = document.getElementById("myCanvas");
    ctx = canvas.getContext("2d");
    var height = 90;
    var width = 40;
    var radius = width / 2;
    ctx.clearRect(0,0, canvas.width, canvas.height);
    ctx.fillStyle = "#FFE2E8";
    ctx.strokeStyle = "black";
    ctx.beginPath();
    ctx.moveTo(20,20);
    ctx.lineTo(70,20);
    ctx.arc(70,40,20, -Math.PI/2, Math.PI/2);
    ctx.lineTo(20,60); 
    ctx.lineTo(20,20);
    ctx.closePath;
    ctx.fill();
    ctx.stroke();
    requestAnimationFrame(draw);

   }

   function init() {
   canvas = document.getElementById("myCanvas");
   ctx = canvas.getContext("2d");
   draw();
   }


   </script>
   </head>

   <body>
   <canvas id="myCanvas" width="400" height="300"     style="background:#00CC66">
   </canvas>
   </body>
   </html>

 var canvas, ctx; canvas = document.getElementById("myCanvas"); ctx = canvas.getContext("2d"); var radius = 20; var width = 70; var margin = 5; var offsetx = -20 var translate = { x: 0, y: 0, xmax: canvas.width - margin - width + offsetx, ymax: canvas.height - margin - width }; var rotate = 0; var to_radians = Math.PI / 180; function draw() { ctx.save(); ctx.translate(translate.x, translate.y); if (translate.x >= translate.xmax) { translate.x = translate.xmax; if (rotate >= 90) { rotate = 90; } else { rotate++; } ctx.rotate(rotate * to_radians); } else { translate.x++; } var height = 90; var width = 40; var radius = width / 2; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = "#FFE2E8"; ctx.strokeStyle = "black"; ctx.beginPath(); ctx.moveTo(20, 20); ctx.lineTo(70, 20); ctx.arc(70, 40, 20, -Math.PI / 2, Math.PI / 2); ctx.lineTo(20, 60); ctx.lineTo(20, 20); ctx.closePath; ctx.fill(); ctx.stroke(); ctx.restore(); requestAnimationFrame(draw); } function init() { canvas = document.getElementById("myCanvas"); ctx = canvas.getContext("2d"); draw(); } init(); 
 <canvas id="myCanvas" width="400" height="300" style="background:#00CC66"> </canvas> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM