Make canvas circle larger - html

I am new to using the canvas html tag and have put a countdown on my website that uses the canvas tag that I think makes the circle and it works ok but would like to make the circles larger but not sure how to do it, I got the coding from https://codepen.io/mdkroon/pen/dBweaL, below is the coding that I currently have. I can't work out how to make the circles larger, I can make the font larger but then the text does not fit in the circles.
<div id="countdown" data-date="2020-01-14" data-time="12:00:00">
<p><strong>Windows 7 End of Life Countdown</strong></p>
<div class="canvas-container" >
<canvas id="days"></canvas>
<canvas id="hours"></canvas>
<canvas id="minutes"></canvas>
<canvas id="seconds"></canvas>
</div>
</div>
<script>
// variables
var countdown = document.getElementById('countdown');
var endDate = countdown.dataset.date || '2020-01-14';
var endTime = countdown.dataset.time || '00:00:00';
var endCountdown = new Date(endDate + 'T' + endTime);
var timer;
var specs = {
'radius': 50,
'centerX': 50,
'centerY': 50,
'thickness': 10,
'offset': -Math.PI/2,
'color': '#1abc9c',
'bgColor': '#ccc',
'idFont': 'small-caps 400 10px Verdana',
'valueFont': 'bold 30px Verdana',
'fontColor': '#000'
};
var time = {
'millisecond': 1000,
'second': 60,
'minute': 60,
'hour': 24,
'day': 365
}
var info = {};
// canvas init
var canvasElements = Array.prototype.slice.call(document.querySelectorAll('canvas'));
var canvasCtx = [];
canvasElements.forEach( function(canvas, index) {
canvas.width = specs.centerX * 2;
canvas.height = specs.centerY * 2;
canvasCtx[index] = canvas.getContext('2d');
var name = canvas.id;
info[name] = {'ctx': index, 'value': 0, 'prevValue': -1};
});
var canvasKeys = Object.keys(info);
info.days.denominator = time.day;
info.hours.denominator = time.hour;
info.minutes.denominator = time.minute;
info.seconds.denominator = time.second;
// show remaining time
function showRemainingTime() {
var now = new Date();
// calculate new values
var secondsLeft = Math.max(0, Math.floor((endCountdown - now)/1000));
info.days.value = Math.floor(secondsLeft / (time.second*time.minute*time.hour));
info.hours.value = Math.floor((secondsLeft % (time.second*time.minute*time.hour)) / (time.second*time.minute));
info.minutes.value = Math.floor((secondsLeft % (time.second*time.minute)) / time.second);
info.seconds.value = Math.floor(secondsLeft % time.second);
// update changed values only
canvasKeys.forEach( function(key) {
if(info[key].value !== info[key].prevValue){
if(key === 'days' && info[key].value > 365) {
// exception if days is more than 1 year
draw(canvasCtx[info[key].ctx], 1, key, info[key].value);
} else {
draw(canvasCtx[info[key].ctx], info[key].value/info[key].denominator, key, info[key].value);
}
info[key].prevValue = info[key].value;
}
});
}
// draw function
function draw(ctx, part, id, value) {
// calculate angles
var start = specs.offset;
var between = 2 * Math.PI * part + specs.offset;
var end = 2 * Math.PI + specs.offset;
// clear canvas
ctx.clearRect(0, 0, specs.centerX * 2, specs.centerY * 2);
// draw remaining %
ctx.fillStyle = specs.color;
ctx.beginPath();
ctx.arc(specs.centerX, specs.centerY, specs.radius, start, between);
ctx.arc(specs.centerX, specs.centerY, specs.radius - specs.thickness, between, start, true);
ctx.closePath();
ctx.fill();
// draw bg
ctx.fillStyle = specs.bgColor;
ctx.beginPath();
ctx.arc(specs.centerX, specs.centerY, specs.radius, between, end);
ctx.arc(specs.centerX, specs.centerY, specs.radius - specs.thickness, end, between, true);
ctx.closePath();
ctx.fill();
// draw text
ctx.fillStyle = specs.fontColor;
ctx.font = specs.idFont;
ctx.fillText(id, specs.radius - ctx.measureText(id).width/2, specs.thickness*3);
ctx.font = specs.valueFont;
ctx.fillText(value, specs.radius - ctx.measureText(value).width/2, specs.radius*2 - specs.thickness*3);
}
// change countdown every second
timer = setInterval(showRemainingTime, 1000);

So that this question does not go unanswered, the solution is to make the radius, centerX, and centerY values in the code sample (and codepen) larger.

Related

How to let a user remove an object in canvas 2D from an arbitrary position

I've got some simple barchart making code written which allows a user to add a barchart but I'd also like to allow them to remove a barchart of choice from the canvas. I don't think this should be overly difficult but I'm relatively new to html and I'm quite unsure how to go about it. Any help would be greatly appreciated.
Here's the code I've written.
<html>
<head>
<script>
var barVals = [];
function draw() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// calculate highest bar value (used to scale the rest)
var highest = 0;
for (var b=0; b<barVals.length; b++) {
if (barVals[b]>highest)
highest=barVals[b];
}
// we have 8 horizontal lines so calculate an appropriate scale
var lineSpacing = 1;
var highestLine = 7*lineSpacing;
while (highestLine<highest) {
lineSpacing *= 10;
highestLine = 7*lineSpacing;
}
// grey background
ctx.fillStyle = "rgb(200,200,200)";
ctx.fillRect (0, 0, 600, 450);
// draw and (if we have any data to scale from) label horizontal lines
var lineNum = 0;
ctx.fillStyle="white";
ctx.font="16px sans-serif";
for (y=0; y<=350; y+=50) {
// line
ctx.beginPath();
ctx.moveTo(50,y+50);
ctx.lineTo(550,y+50);
ctx.stroke();
// label (the 6 is an offset to centre the text vertically on the line)
if (barVals.length>0) {
ctx.fillText(lineSpacing*lineNum, 10, 400-y+6);
lineNum++;
}
}
// draw boxes (widths based on how many we have)
var barWidth = 500/barVals.length;
var halfBarWidth = barWidth/2;
for (b=0; b<barVals.length; b++) {
// calculate size of box and draw it
var x = 60+b*barWidth;
var hgt = (barVals[b]/highestLine)*350; // as fraction of highest line
if (b%2==0)
ctx.fillStyle = "red";
else
ctx.fillStyle = "blue";
ctx.fillRect(x,400-hgt,barWidth,hgt);
// calculate position of text and draw it
ctx.fillStyle="white";
var metrics = ctx.measureText(barVals[b]);
var halfTextWidth = metrics.width/2;
x = 60+halfBarWidth+(b*barWidth)-halfTextWidth;
ctx.fillText(barVals[b], x, 420-hgt);
}
}
function addBar() {
var textBoxObj = document.getElementById("barVal");
barVals.push(parseInt(textBoxObj.value)); // add new value to end of array. As an integer not a string!!
draw(); // redraw
textBoxObj.value = 0;
}
</script>
</head>
<body onload="draw();">
<center>
<canvas id="canvas" width="600" height="450"></canvas>
<form>
<BR>
<input type=button value='Add Bar' onclick='addBar();'> <input id='barVal' value=0>
</form>
</body>
</html>
Removing a specific chart isn't much different from adding. In fact you almost have everything you need right in your code yet.
Let's take a look at it. As soon as you click on the "Add Bar" button it will add a value from the associated textbox to the barVal array. For example, if there has been a value of 5 and 12 and you would trace the contents of barVal to the console using
console.log(barVal);
you would see this
Array [ 5, 12 ]
So 5 is stored at the first position and 12 at the second inside the array. With this knowledge in mind, what about adding a function which simply removes a specific element from the array? Here comes the array.splice() function into play. You can pass it an index inside the array and a number of elements it should remove.
e.g. if we want to get rid of the 12, we'd call barVal.splice(1,1);
After the element has been removed it's just a matter of updating your graph by calling draw() again. Now you might wonder why we pass 1 as the index, as we want to remove the second element - that's because indexes start counting from 0.
Here's an example:
var barVals = [];
function draw() {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// calculate highest bar value (used to scale the rest)
var highest = 0;
for (var b = 0; b < barVals.length; b++) {
if (barVals[b] > highest)
highest = barVals[b];
}
// we have 8 horizontal lines so calculate an appropriate scale
var lineSpacing = 1;
var highestLine = 7 * lineSpacing;
while (highestLine < highest) {
lineSpacing *= 10;
highestLine = 7 * lineSpacing;
}
// grey background
ctx.fillStyle = "rgb(200,200,200)";
ctx.fillRect(0, 0, 600, 450);
// draw and (if we have any data to scale from) label horizontal lines
var lineNum = 0;
ctx.fillStyle = "white";
ctx.font = "16px sans-serif";
for (y = 0; y <= 350; y += 50) {
// line
ctx.beginPath();
ctx.moveTo(50, y + 50);
ctx.lineTo(550, y + 50);
ctx.stroke();
// label (the 6 is an offset to centre the text vertically on the line)
if (barVals.length > 0) {
ctx.fillText(lineSpacing * lineNum, 10, 400 - y + 6);
lineNum++;
}
}
// draw boxes (widths based on how many we have)
var barWidth = 500 / barVals.length;
var halfBarWidth = barWidth / 2;
for (b = 0; b < barVals.length; b++) {
// calculate size of box and draw it
var x = 60 + b * barWidth;
var hgt = (barVals[b] / highestLine) * 350; // as fraction of highest line
if (b % 2 == 0)
ctx.fillStyle = "red";
else
ctx.fillStyle = "blue";
ctx.fillRect(x, 400 - hgt, barWidth, hgt);
// calculate position of text and draw it
ctx.fillStyle = "white";
var metrics = ctx.measureText(barVals[b]);
var halfTextWidth = metrics.width / 2;
x = 60 + halfBarWidth + (b * barWidth) - halfTextWidth;
ctx.fillText(barVals[b], x, 420 - hgt);
}
}
function addBar() {
var textBoxObj = document.getElementById("barVal");
barVals.push(parseInt(textBoxObj.value)); // add new value to end of array. As an integer not a string!!
draw(); // redraw
textBoxObj.value = 0;
}
function removeBar() {
var textBoxObj = document.getElementById("removeBarVal");
barVals.splice(parseInt(textBoxObj.value), 1);
draw(); // redraw
}
draw();
<center>
<canvas id="canvas" width="600" height="450"></canvas>
<form>
<br>
<input type=button value='Add Bar' onclick='addBar();'> <input id='barVal' value=0>
<input type=button value='Remove Bar' onclick='removeBar();'> <input id='removeBarVal' value=0>
</form>
</center>

HTML Canvas to WPF XAML Canvas

I have an ASP.NET application that allows users to click or tap on a Canvas to indicate pain locations on a body image. A body image is displayed on the Canvas and is the same size as the Canvas.
function drawBodyMap() {
var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');
var imageObj = new Image();
imageObj.src = 'https://.../body.jpg';
imageObj.onload = function () {
ctx.drawImage(imageObj, 0, 0, 600, 367);
};
}
<canvas id="myCanvas" width="600" height="367"></canvas>
<script>
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
canvas.addEventListener('mouseup', function (evt) {
if (ixPos > 9)
return;
var mousePos = getMousePos(canvas, evt);
bodyX[ixPos] = mousePos.x;
bodyY[ixPos] = mousePos.y;
painType[ixPos] = pain_type;
ixPos++;
ctx.beginPath();
ctx.arc(mousePos.x, mousePos.y, 8, 0, 2 * Math.PI);
if (pain_type == 1)
ctx.fillStyle = "#DC143C";
else if (pain_type == 2)
ctx.fillStyle = "#EA728A";
else if (pain_type == 3)
ctx.fillStyle = "#DAA520";
else if (pain_type == 4)
ctx.fillStyle = "#008000";
else if (pain_type == 5)
ctx.fillStyle = "#4169E1";
ctx.fill();
}, false);
</script>
The X,Y points added to the Canvas on the body image are saved to a database. These points are then loaded into a WPF application that displays the same body image on an XAML Canvas. C# code then adds the points over the image.
WPF CODE:
private void DisplayBodyPain()
{
List<BodyPain> pain = gFunc.sws.GetBodyPain(MemberID);
foreach (BodyPain bp in pain)
{
Border b = new Border();
b.Tag = bp.PainType.ToString();
b.Cursor = Cursors.Hand;
b.Width = 16;
b.Height = 16;
b.CornerRadius = new CornerRadius(8);
b.Background = GetPainBrush((byte)bp.PainType);
cvsBody.Children.Add(b);
Canvas.SetTop(b, bp.YPos);
Canvas.SetLeft(b, bp.XPos);
}
}
The problem I have is that the points drawn on the XAML Canvas are all slightly different from the points that were drawn on the HTML Canvas. Each point is not in exactly the same location.
Is there a way I can fix this? Should I be doing it differently?
HTML Canvas
WPF Canvas
I think you need to subtract the size of the marker from the coordinate where you want to place it. For the last two lines, try this instead:
Canvas.SetTop(b, bp.YPos - (b.Height / 2));
Canvas.SetLeft(b, bp.XPos - (b.Width / 2));
By subtracting half the marker's height and width, the center of the marker is placed on the desired coordinates.

HTML5 canvas drawing on background scalling

i have problem i have background image and changing it scale and position with mousewheel and can drawing with mousedown and mousemove events. me example: http://jsfiddle.net/74MCQ/ Now see first drawing and second zoom we don't see drawing lines. I need make like a paint if drawing on me select position and if zoom i need see equal position with equal zoom scale.
You need a way to store the drawings of your user, either within another canvas, or by storing coordinates.
I suggest you store coordinates, below here's some code that will store the lines within an array, each line being an array of coordinates like : [x0, y0, x1, y1, x2, y2, ... ].
Edit : now i simplified the things, the coordinates are stored relative to the center of canvas.
See the fiddle, it is mostly working.
fiddle :
http://jsfiddle.net/gamealchemist/74MCQ/4/
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
var x = evt.clientX - rect.left;
var y = evt.clientY - rect.top;
var sx = (x-cw/2)/scale;
var sy = (y-ch/2)/scale;
return {
x: x,
y: y,
sx : sx,
sy:sy
};
}
/****** PAINT ******/
var isDrawing = false;
var color = "#000000";
var brushWidth = 10;
//var previousEvent = false;
ctx.strokeStyle = '#000000';
var currentLine = null;
var allLines = [];
$("#canvas").mousedown(function (e) {
var mousePos = getMousePos(canvas, e);
ctx.moveTo(mousePos.x, mousePos.y);
isDrawing = true;
if (currentLine) allLines.push(currentLine);
currentLine = [];
currentLine.push(mousePos.sx, mousePos.sy);
});
$("#canvas").mouseup(function () {
isDrawing = false;
if (currentLine) allLines.push(currentLine);
currentLine = null;
});
$("#canvas").mouseout(function () {
isDrawing = false;
if (currentLine) allLines.push(currentLine);
currentLine = null;
});
$("#canvas").mousemove(function (e) {
if (isDrawing === true) {
var mousePos = getMousePos(canvas, e);
currentLine.push(mousePos.sx, mousePos.sy);
//paint tools, effects
ctx.lineWidth = 10;
ctx.strokeStyle = color;
ctx.shadowBlur = 1;
ctx.shadowColor = 'rgb(0, 0, 0)';
ctx.lineTo(mousePos.x, mousePos.y);
ctx.stroke();
}
});
function drawStoredLines() {
var thisLine;
for (var i = 0; i < allLines.length; i++) {
thisLine = allLines[i];
drawLine(thisLine);
}
}
function drawLine(ptArray) {
if (ptArray.length <= 2) return;
ctx.beginPath();
ctx.moveTo(ptArray[0], ptArray[1]);
for (var p = 2; p < ptArray.length; p += 2) {
ctx.lineTo(ptArray[p], ptArray[p + 1]);
}
ctx.lineWidth = 10;
ctx.strokeStyle = color;
ctx.shadowBlur = 1;
ctx.shadowColor = 'rgb(0, 0, 0)';
ctx.stroke();
}
Notice that i couldn't resist reducing your 175 lines code to select the scale to a 25 lines one :-)
var zoomSteps = [0.1, 0.2, 0.4, 0.6, 0.8, 1.0, 1.5, 2.0, 3.0, 4.0];
var zoomIndex = zoomSteps.indexOf(1);
function doScroll(e) {
e = window.event || e;
var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
zoomIndex = zoomIndex + delta;
if (zoomIndex < 0) zoomIndex = 0;
if (zoomIndex >= zoomSteps.length) zoomIndex = zoomSteps.length - 1;
scale = zoomSteps[zoomIndex];
imageWidthZoomed = imageWidth * scale;
imageHeightZoomed = imageHeight * scale;
var mousePos = getMousePos(canvas, e);
draw(mousePos.x, mousePos.y, scale);
}

How to add hover effect for each slice (html5 canvas)

hi can u help me to setup this code. I m not so good at html5.
This text is displayed if your browser does not support HTML5 Canvas.
$(document).ready(function() {
// initialize some variables for the chart
var
canvas = $("#canvas")[0];
var ctx = canvas.getContext('2d');
var data = [75,68,32,95,20,51];
var colors = ["#7E3817", "#C35817", "#EE9A4D", "#A0C544", "#348017", "#307D7E"];
var center = [canvas.width / 2, canvas.height / 2];
var radius = Math.min(canvas.width, canvas.height) / 2;
var lastPosition = 0, total = 0;
var pieData = [];
// total up all the data for chart
for (var i in data) { total += data[i]; }
// populate arrays for each slice
for(var i in data) {
pieData[i] = [];
pieData[i]['value'] = data[i];
pieData[i]['krasa'] = colors[i];
pieData[i]['startAngle'] = 2 * Math.PI * lastPosition;
pieData[i]['endAngle'] = 2 * Math.PI * (lastPosition + (data[i]/total));
lastPosition += data[i]/total;
}
function drawChart()
{
for(var i = 0; i < data.length; i++)
{
var gradient = ctx.createLinearGradient( 0, 0, canvas.width, canvas.height );
gradient.addColorStop( 0, "#ddd" );
gradient.addColorStop( 1, colors[i] );
ctx.beginPath();
ctx.moveTo(center[0],center[1]);
ctx.arc(center[0],center[1],radius,pieData[i]['startAngle'],pieData[i]['endAngle'],false);
ctx.lineTo(center[0],center[1]);
ctx.closePath();
ctx.fillStyle = gradient;
ctx.fill();
ctx.lineWidth = 1;
ctx.strokeStyle = "#fff";
ctx.stroke();
}
}
drawChart(); // first render
});
How to add hover effect for each slice?
After you have drawn your wedges to the canvas, they become just pixels in a larger image.
You have no way to track the individual pie wedges at this point. Therefore no way to track hovers on any particular wedge.
But...You do have several options!
Option#1 --- Make your own hit-test to determine which pie wedge you clicked on.
It would look something like this (I HAVE NOT TESTED THIS !!!)
var chartStartAngle=0; // you started drawing the pie at angle 0
function handleChartClick ( clickEvent ) {
// Get the mouse cursor position at the time of the click, relative to the canvas
var mouseX = clickEvent.pageX - this.offsetLeft;
var mouseY = clickEvent.pageY - this.offsetTop;
// Was the click inside the pie chart?
var xFromCenter = mouseX - center[0];
var yFromCenter = mouseY - center[1];
var distanceFromCenter = Math.sqrt( Math.pow( Math.abs( xFromCenter ), 2 ) + Math.pow( Math.abs( yFromCenter ), 2 ) );
if ( distanceFromCenter <= radius ) {
// You clicked inside the chart.
// So get the click angle
var clickAngle = Math.atan2( yFromCenter, xFromCenter ) - chartStartAngle;
if ( clickAngle < 0 ) clickAngle = 2 * Math.PI + clickAngle;
for ( var i in pieData ) {
if ( clickAngle >= pieData[i]['startAngle'] && clickAngle <= pieData[i]['endAngle'] ) {
// You clicked on pieData[i]
// So do your effect here!
return;
}
}
}
}
Option#2 --- Use a cavas library which allows you to keep track of each wedge in your pie chart and therefore do your hover effect. Several good libraries (among many good ones) are: EaselJs, FabricJs and KineticJs.
Elated.com has a great tutorial that shows what you're looking for. Check it out: http://www.elated.com/articles/snazzy-animated-pie-chart-html5-jquery/

moving an image across a html canvas

I am trying to move an image from the right to the center and I am not sure if this is the best way.
var imgTag = null;
var x = 0;
var y = 0;
var id;
function doCanvas()
{
var canvas = document.getElementById('icanvas');
var ctx = canvas.getContext("2d");
var imgBkg = document.getElementById('imgBkg');
imgTag = document.getElementById('imgTag');
ctx.drawImage(imgBkg, 0, 0);
x = canvas.width;
y = 40;
id = setInterval(moveImg, 0.25);
}
function moveImg()
{
if(x <= 250)
clearInterval(id);
var canvas = document.getElementById('icanvas');
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
var imgBkg = document.getElementById('imgBkg');
ctx.drawImage(imgBkg, 0, 0);
ctx.drawImage(imgTag, x, y);
x = x - 1;
}
Any advice?
This question is 5 years old, but since we now have requestAnimationFrame() method, here's an approach for that using vanilla JavaScript:
var imgTag = new Image(),
canvas = document.getElementById('icanvas'),
ctx = canvas.getContext("2d"),
x = canvas.width,
y = 0;
imgTag.onload = animate;
imgTag.src = "http://i.stack.imgur.com/Rk0DW.png"; // load image
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // clear canvas
ctx.drawImage(imgTag, x, y); // draw image at current position
x -= 4;
if (x > 250) requestAnimationFrame(animate) // loop
}
<canvas id="icanvas" width=640 height=180></canvas>
drawImage() enables to define which part of the source image to draw on target canvas. I would suggest for each moveImg() calculate the previous image position, overwrite the previous image with that part of imgBkg, then draw the new image. Supposedly this will save some computing power.
Here's my answer.
var canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
var myImg = new Image();
var myImgPos = {
x: 250,
y: 125,
width: 50,
height: 25
}
function draw() {
myImg.onload = function() {
ctx.drawImage(myImg, myImgPos.x, myImgPos.y, myImgPos.width, myImgPos.height);
}
myImg.src = "https://mario.wiki.gallery/images/thumb/c/cc/NSMBUD_Mariojump.png/1200px-NSMBUD_Mariojump.png";
}
function moveMyImg() {
ctx.clearRect(myImgPos.x, myImgPos.y, myImgPos.x + myImgPos.width, myImgPos.y +
myImgPos.height);
myImgPos.x -= 5;
}
setInterval(draw, 50);
setInterval(moveMyImg, 50);
<canvas id="canvas" class="canvas" width="250" height="150"></canvas>
For lag free animations,i generally use kinetic.js.
var stage = new Kinetic.Stage({
container: 'container',
width: 578,
height: 200
});
var layer = new Kinetic.Layer();
var hexagon = new Kinetic.RegularPolygon({
x: stage.width()/2,
y: stage.height()/2,
sides: 6,
radius: 70,
fill: 'red',
stroke: 'black',
strokeWidth: 4
});
layer.add(hexagon);
stage.add(layer);
var amplitude = 150;
var period = 2000;
// in ms
var centerX = stage.width()/2;
var anim = new Kinetic.Animation(function(frame) {
hexagon.setX(amplitude * Math.sin(frame.time * 2 * Math.PI / period) + centerX);
}, layer);
anim.start();
Here's the example,if you wanna take a look.
http://www.html5canvastutorials.com/kineticjs/html5-canvas-kineticjs-animate-position-tutorial/
Why i suggest this is because,setInterval or setTimeout a particular function causes issues when large amount of simultaneous animations take place,but kinetic.Animation deals with framerates more intelligently.
Explaining window.requestAnimationFrame() with an example
In the following snippet I'm using an image for the piece that is going to be animated.
I'll be honest... window.requestAnimationFrame() wasn't easy for me to understand, that is why I coded it as clear and intuitive as possible. So that you may struggle less than I did to get my head around it.
const
canvas = document.getElementById('root'),
btn = document.getElementById('btn'),
ctx = canvas.getContext('2d'),
brickImage = new Image(),
piece = {image: brickImage, x:400, y:70, width:70};
brickImage.src = "https://i.stack.imgur.com/YreH6.png";
// When btn is clicked execute start()
btn.addEventListener('click', start)
function start(){
btn.value = 'animation started'
// Start gameLoop()
brickImage.onload = window.requestAnimationFrame(gameLoop)
}
function gameLoop(){
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height)
// Draw at coordinates x and y
ctx.drawImage(piece.image, piece.x, piece.y)
let pieceLeftSidePos = piece.x;
let middlePos = canvas.width/2 - piece.width/2;
// Brick stops when it gets to the middle of the canvas
if(pieceLeftSidePos > middlePos) piece.x -= 2;
window.requestAnimationFrame(gameLoop) // Needed to keep looping
}
<input id="btn" type="button" value="start" />
<p>
<canvas id="root" width="400" style="border:1px solid grey">
A key point
Inside the start() function we have:
brickImage.onload = window.requestAnimationFrame(gameLoop);
This could also be written like: window.requestAnimationFrame(gameLoop);
and it would probably work, but I'm adding the brickImage.onload to make sure that the image has loaded first. If not it could cause some issues.
Note: window.requestAnimationFrame() usually loops at 60 times per second.