Update canvas drawing on click with Javascript - javascript

I'm trying to increase the radius of a circle drawn in canvas using JavaScript functions.
There were many topics with similar issues but couldn't find an answer that would fix this one, I've tried using built-in methods that were suggested like setInterval, setTimeout, window.requestAnimationFrame and clearing the canvas to redraw the circle with the updated variable.
So far the setInterval method displayed the update but kept the previous iterations in the canvas, the clear method doesn't work.
Here's the example :
//Define globals
var radiusIncrement = 5;
var ballRadius = 20;
//Helper functions
function increaseRadius() {
ballRadius += radiusIncrement;
}
function decreaseRadius() {
if (ballRadius > 0) {
ballRadius -= radiusIncrement;
}
}
//Draw handler
function draw() {
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(canvas.height/2,canvas.width/2,ballRadius,0,2*Math.PI);
ctx.stroke();
}
//Event handler
setInterval(function() {
draw();
ctx.clearRect(0,0,canvas.width,canvas.height);
}, 100);
<!--Create frame and assign callbacks to event handlers-->
<button type="button" onclick="increaseRadius()">Increase Radius</button>
<button type="button" onclick="decreaseRadius()">Decrease Radius</button>
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #000000;"></canvas>
Rather than using setInterval, is there a way to streamline the code using and use an event handler to refresh the canvas on every onlick ?
Thanks for your help.
Cheers.

If I understand you correctly, you only want to redraw on the button click, i.e. on a radius change. You don't need any timing functions for this, you can call the draw function whenever a radius change happens:
//Define globals
var radiusIncrement = 5;
var ballRadius = 20;
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
//initialize
draw();
//Helper functions
function increaseRadius() {
ballRadius += radiusIncrement;
draw();
}
function decreaseRadius() {
if (ballRadius > 0) {
ballRadius -= radiusIncrement;
draw();
}
}
//Draw handler
function draw() {
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.arc(canvas.height/2,canvas.width/2,ballRadius,0,2*Math.PI);
ctx.stroke();
}
As you can see I also extracted the variable definition for canvas and ctx out of the draw function, since you don't need to re-assign these on every draw call.

Related

Drawing a canvas line based on variables

I'm working with Arduino and I'm using an Accelerometer. I want to make a 2D line based on the x and y variables from the accelerometer.
I'm trying to it with this code:
board.on("ready", () => {
const accelerometer = new Accelerometer({
controller: "MPU6050"
});
accelerometer.on("change", function () {
const {
acceleration,
inclination,
orientation,
pitch,
roll,
x,
y,
z
} = accelerometer;
const $yPos = y * 100 * 10;
const $canvas = document.querySelector(`.simulation__line`);
if ($canvas.childElementCount > 0) {
$canvas.innerHTML = ``;
}
const drawing = $canvas.getContext("2d");
drawing.beginPath();
drawing.moveTo(1000, 1000 - $yPos);
drawing.lineTo(0, 1000);
drawing.lineTo(-1000, 1000 + $yPos);
drawing.stroke();
drawing.clearRect(1000, $yTest, drawing.width, drawing.height);
});
});
So every time the accelerometer changes variables, it draws a new line. This results in a lot of lines, but I want only one which is constantly changing. I tried to do it with the if statement if ($canvas.childElementCount > 0), but this won't help.
Here is a very simple example of drawing something on a canvas with a variable.
I believe your issue is in the way you are using the clearRect to clear the canvas
<input type="range" min="1" max="99" value="10" id="slider" oninput="draw()">
<br/>
<canvas id="canvas"></canvas>
<script>
function draw() {
y = document.getElementById("slider").value
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(0, y, 250, 3);
}
// init canvas
var canvas = document.getElementById('canvas');
canvas.height = (canvas.width = 250)/2;
var ctx = canvas.getContext('2d');
draw();
</script>
Run that code snippet to see it in action.
The slider controls the Y position of a "line" that I'm drawing in the canvas, there should be just one line visible on the screen at any time.
The key is to wipe the screen:
ctx.clearRect(0, 0, canvas.width, canvas.height);
before we draw anything
Looking at your code you are doing a few things inside the "accelerometer change" function that you should consider doing outside here is what I mean:
const $canvas = document.querySelector(`.simulation__line`);
const drawing = $canvas.getContext("2d");
Those should not be changing as the accelerometer changes so I would keep them out
The other sticky point is your call to:
drawing.clearRect(1000, $yTest, drawing.width, drawing.height);
that should be the first before you start drawing anything
not sure why to start at 1000, $yTest you should clear the entire canvas start at 0,0
and the drawing.width, drawing.height are not the same as canvas.width, canvas.height if I change that on my example it certainly will not wipe the canvas

Drawing objects on canvas created by eventlisteners()

I am new to JavaScript and I am having a hard time understanding how to get the canvas to cooperate with stuff I want to do.
I am trying to have my HTML button outside the canvas create a rectangle on the canvas. Then I want the rectangle to fall. I have the canvas animated, I have the button set to create a rectangle at user inputted coordinates, but...the canvas won't animate it.
It won't fall like the statically created rectangles. I also am struggling with how to get my button to create a new rectangle each time instead of redrawing the same one? Hoping someone can explain more than just give me the code.
Thanks in advance.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
window.onload = addListeners;
function addListeners() {
document.getElementById('b1').addEventListener('click',btn1,false);
function btn1() {
var inputx = document.getElementById("work").value;
var inputy = document.getElementById("y").value;
var inputs = document.getElementById("s").value;
new Rectangle(inputx,inputy,inputs);
// rec.x = inputx;
//rec.y = inputy;
//rec.s = inputs;
}
}
var r2 = new Rectangle(500, 50, 50);
var rec = new Rectangle();
//animate
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0,0,1450,250);
r2.draw();
r2.update();
rec.draw();
rec.update();
}
code for rectangle:
function Rectangle(x,y,s){
this.x = x;
this.y = y;
this.s = s;
this.draw = function(){
//console.log('fuck');
ctx.fillStyle = "rgba(0,200,0,1)";
ctx.fillRect(this.x,this.y,this.s,this.s);
}
this.update = function(){
console.log(this.y);
if((this.y + this.s) <= 250){
this.y= this.y+2;
}
}
}
The button is not animating anything as the animate method was not being called. Also in your code when you called animate it ended in an infinite loop as requestAnimationFrame will continue to call animate repeatedly, so I've added a condition around requestAnimationFrame(animate) to check the squares height and stop running it when it reaches the bottom, similar to what you had in your update function.
To create a new square every time you click the button, I moved the creation of the Rectangles inside the btn1 function. If you want to keep the old squares while creating new ones, you will need to keep track of them outside the canvas and redraw them with everything else each animation.
I guessed what your html looks like, but you can run the code below it will drop two squares, but note that the stop condition is only on the hard coded one.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
document.getElementById("b1").addEventListener("click", btn1, false);
var r2;
var rec;
function btn1() {
var inputx = document.getElementById("work").value;
var inputy = document.getElementById("y").value;
var inputs = document.getElementById("s").value;
r2 = new Rectangle(500, 50, 50);
rec = new Rectangle(parseInt(inputx, 10), parseInt(inputy, 10), parseInt(inputs, 10));
animate();
}
//animate
function animate() {
if (r2.y + r2.s <= 400) {
requestAnimationFrame(animate);
}
ctx.clearRect(0,0,1450,400);
r2.draw();
r2.update();
rec.draw();
rec.update();
}
function Rectangle(x,y,s){
this.x = x;
this.y = y;
this.s = s;
this.draw = function(){
ctx.fillStyle = "rgba(0,200,0,1)";
ctx.fillRect(this.x,this.y,this.s,this.s);
}
this.update = function(){
this.y= this.y+2;
}
}
<div>
<input id='work'>
<input id='y'>
<input id='s'>
<button id="b1"> Create Sqaure</button>
</div>
<canvas id="myCanvas" width=600 height=400></canvas>

Gradually fade to colour using JS

I am trying to make a rectangle gradually change its colour (fade) from yellow to white using Javascript after a button is pressed. Sadly my code does not work. Could you help me figure out what is wrong with the code and how to fix it?
I have just begun studying Javascript. Sorry, if this question is stupid. Thank you in advance.
This is my code:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas> // create canvas to work with
<button onclick="fade(ctx)">Change the colour!</button>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d"); //set context
ctx.rect(20, 20, 150, 100); // draw a rectangle
ctx.stroke(); // with border
ctx.fillStyle="#FFFF00"; // fill with yellow
ctx.fillRect(20,20,150,100);
function fade(ctx) { // fade function responsible for changing colour
var dom = getElementById(ctx), level = 1; // new object based on rectangle object, initial iterator is set to 1
function step() { // inner step function
var h = level.toString(16);
dom.fillStyle = '#FFFF' + h + h; // construct a new colour using h variable
if (level < 15) {
level += 1;
setTimeout(step, 100); // do this after every 100 ms
}
}
setTimeout(step, 100);
}
</script>
</body>
</html>
You almost have it with your code though. You are passing the context into the function already so no need for the getElementById(ctx) bit. In fact that will give you an error so remove that line from your code. Instead directly set the fillStyle on the ctx variable like this:
ctx.fillStyle = '#FFFF' + h + h;
and you also need to redraw the rectangle, so add this line:
ctx.fillRect(20,20,150,100);
after you set the colour. And that will do it.

Drawing a path on canvas using for loop in javascript

I want to draw a path on canvas using a for loop. I do not want to draw the normal way, I need to use a for loop. Now, the coords work perfectly, but the problem is that the last click draws lines to each of the previous clicks, while I only want to draw a path. I know that I should make a copy of the "i" but I can't make it work.
function draw(event) {
var coords = getMouseCoords(event);
xpos = coords[0];
ypos = coords[1];
for(i=0; i<myArray.length; i++) {
context.beginPath();
context.moveTo(coords[0], coords[1]);
context.lineTo(myArray[i].x, myArray[i].y);
context.stroke();
}
myArray.push({x:coords[0], y:coords[1]});
}
HTML
<canvas width="600" height="480" id="myCanvas" onclick="draw(event)"></canvas>
Could you take a look at it and see if you can fix the problem? No JQuery please.
Thanks,
Marco
You wanted to use for loop, solution below draws path each time function draw is invoked, but keep in mind that it makes sense only when canvas is cleared before drawing. Otherwise you could draw line from current click location to last element of array and the result would be the same.
Also replace var coords = [event.clientX, event.clientY]; with call to your function, I have changed it to make snippet work.
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var myArray = [];
function draw(event) {
var coords = [event.clientX, event.clientY];
xpos = coords[0];
ypos = coords[1];
myArray.push({
x: coords[0],
y: coords[1]
});
if (myArray.length > 1) {
for (i = 0; i < myArray.length - 1; i++) {
context.beginPath();
context.moveTo(myArray[i].x, myArray[i].y);
context.lineTo(myArray[i + 1].x, myArray[i + 1].y);
context.stroke();
}
}
}
<canvas width="600" height="480" id="myCanvas" onclick="draw(event)"></canvas>

HTML5 Canvas Drawing History

I'm curious to know how applications such as Adobe Photoshop implement their drawing history with the ability to go back or undo strokes on rasterized graphics without having to redraw each stroke from the beginning...
I'm wanting to implement a similar history function on an HTML5 drawing application I'm working on but duplicating the canvas after every stoke seems like it'd use too much memory to be a practical approach, especially on larger canvas'...
Any suggestions on how this might be implemented in a practical and efficient manner?
I may have a solution.....
var ctx = document.getElementById("canvasId").getContext("2d");
var DrawnSaves = new Array();
var Undo = new Array();
var FigureNumber = 0;
var deletingTimer;
function drawLine(startX, startY, destX, destY) {
ctx.beginPath();
ctx.moveTo(startX, startY);
ctx.lineTo(destX, destY);
ctx.stroke();
var Para = new Array();
Para["type"] = "line";
Para["fromX"] = startX;
Para["fromY"] = startY;
Para["toX"] = destX;
Para["toY"] = destY;
DrawnSaves.push(Para);
FigureNumber++;
}
function undo() {
ctx.beginPath();
ctx.clearRect(0, 0, 500, 500);
Undo[FigureNumber] = DrawnSaves[FigureNumber];
DrawnSaves[FigureNumber] = "deleted";
FigureNumber--;
drawEverything();
startTimeoutOfDeleting();
}
function undoTheUndo() {
FigureNumber++;
DrawnSaves[FigureNumber] = Undo[FigureNumber];
drawEverything();
clearTimeout(deletingTimer);
}
function drawEverything() {
for (i = 0; i < DrawnSaves.length; i++) {
if (DrawnSaves[i].type == "line") {
ctx.beginPath();
ctx.moveTo(DrawnSaves[i].fromX, DrawnSaves[i].fromY);
ctx.lineTo(DrawnSaves[i].toX, DrawnSaves[i].toY);
ctx.stroke();
}
}
}
function startTimeoutOfDeleting() {
setTimeout(function() {Undo[FigureNumber] = "deleted";}, 5000);
}
This is really simple, first I draw a line when the function is called and save all his parameters in an array. Then , in the undo function I just start a timer do delete the figure drawn i 2000 miliseconds, clears the whole canvas and makes it can't be redrawn. in the undoTheUndo function, it stops the timer to delete the figure and makes that the figure can be redrawn. In the drawEverything function, it draws everything in the array based on it's type ("line here"). That's it... :-)
Here is an example working : This, after 2sec UNDOs then after 1sec UNDOTHEUNDO

Categories