[英]Moving and rotating with HTML5
需要做的事情:粉红色的对象应该从左向右移动(本身)。 然后,如果距边缘5像素,则应旋转90度。
有谁知道如何做到这一点?
我已经很长时间没有学习JavaScript了,这是我第一次使用HTML5创建东西。 因此,这是全新的。 我真的希望您能帮助我更好地理解代码以及如何使其移动和旋转。
<!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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.