HTML5 canvas cung cấp các phương thức cần thiết để vẽ hình ảnh và xóa hoàn toàn. Chúng ta có thể nhờ JavaScript để mô phỏng hoạt ảnh tốt trên HTML5 canvas.
Ví dụ
Bạn có thể thử chạy mã sau để thực hiện hoạt ảnh cơ bản HTML5 Canvas −
<!DOCTYPE HTML> <html> <head> <script> var pattern= new Image(); function animate(){ pattern.src = '/html5/images/pattern.jpg'; setInterval(drawShape, 100); } function drawShape(){ // lấy phần tử canvas bằng DOM var canvas = document.getElementById('mycanvas'); // Đảm bảo không thực thi khi canvas không được hỗ trợ if (canvas.getContext){ // sử dụng getContext để dùng canvas cho vẽ var ctx = canvas.getContext('2d'); ctx.fillStyle = 'rgba(0,0,0,0.4)'; ctx.strokeStyle = 'rgba(0,153,255,0.4)'; ctx.save(); ctx.translate(150,150); var time = new Date(); ctx.rotate( ((2*Math.PI)/6)*time.getSeconds() + ( (2*Math.PI)/6000)*time.getMilliseconds() ); ctx.translate(0,28.5); ctx.drawImage(pattern,-3.5,-3.5); ctx.restore(); } else { alert('Bạn cần Safari hoặc Firefox 1.5+ để xem demo này.'); } } </script> </head> <body onload="animate();"> <canvas id="mycanvas" width="400" height="400"></canvas> </body> </html>