Read first: HTML5 canvas draw animated circle
HTML:
<canvas id="myCanvas" width="600" height="600"></canvas>
CSS:
body { margin: 0px; padding: 0px; }
Javascript:
var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d'); var myCircle = { x: 20, y: 20, radius: 20, color: "red", borderwidth: 1, bordercolor: '#003300', txt: "TutorialSpots", txtcolor: 'blue', txtfont: 'Calibri' }; function draw(){ //speed: pixels per second Speed = 60; directionAngle = Math.PI / 6;//30d myCircle.x += Speed /60 * Math.cos(directionAngle) ; myCircle.y += Speed /60 * Math.sin(directionAngle) ; context.clearRect(0,0,canvas.width,canvas.height); context.beginPath(); context.arc(myCircle.x, myCircle.y, myCircle.radius, 0, 2 * Math.PI, false); context.fillStyle = myCircle.color; context.fill(); context.lineWidth = myCircle.borderwidth; context.strokeStyle = myCircle.bordercolor; context.stroke(); context.font = myCircle.radius+'px '+myCircle.txtfont; context.fillStyle = myCircle.txtcolor; context.fillText(myCircle.txt, myCircle.x-context.measureText(myCircle.txt).width/2, myCircle.y+myCircle.radius/4); } setInterval(draw ,1000/60)
Try it Yourself:
https://jsfiddle.net/qfs8entc/1/
In this tutorial, we can learn how to determine the text width in canvas by use measureText method.
Read more: HTML5 canvas: a circle follows the mouse
1 Comment
HTML5 canvas: a circle follows the mouse | Free Online Tutorials
(August 28, 2015 - 9:13 am)[…] Read first: HTML5 canvas: Draw a circle move any direction […]