How to remove text from canvas in Javascript - javascript

My problem is that when I am clicking on button, callfunction() method called and counter is incremented by 5, when I am again click counter incremented by 5 and displayed 10 on given location my problem is that when counter is incremented previous number is not erased and displayed incremented number on previous number. I want to remove previous number and display next incremented number. I have following code:
var count=0;
function callfunction()
{
context.fillText(count,200,200);
count = count+5;
//context.fillText("",200,200);
}

fillText with background colour, if it's monochromatic. Or preserve what was there before as image data, then paste it over later when you want to erase the text.

The only way i know is to clear the full canvas element using canvas.fillRect.
Please see this jsFiddle for an example.

count = 0;
function update(){
canvas.clearRect(0,0,canvas.width,canvas.height);
canvas.fillText(count,200,200);
//Draw anything else...
}
setInterval("update()",1000/60); //60 Frames per second
button.onclick = function(){ //Change button to your button element
count += 5;
}
This should work!

You can use clearRect() to just clear a portion of the canvas...
If you know the size of your text field, set clearRect() to a rectangle large enough to clear that text field:
var count=0;
function callfunction()
{
context.clearRect(200, 190, 50, 10); // clears a text field 50 x 10, above baseline
context.fillText(count,200,200);
count = count+5;
}

Try clearing the canvas first:
var count=0;
function callfunction()
{
context.clearRect ( 0 , 0 ,canvas.height , canvas.width );
context.fillText(count,200,200);
count = count+5;
//context.fillText("",200,200);
}

Related

Loop gif n number of times with p5js

I'm trying to build a simple interaction where users input two numbers, have a gif loop a number of times equal to the sum of those numbers, and then have the gif freeze on the first frame (with an option to reset the process). I think I have figured out how to do almost all of this in p5, except for the gif looping.
Is there a way to control the loops of a gif in p5js? Is there a better way to approach this task? Animating a sprite or something would largely achieve the same goals if that was a wiser approach.
thank you!
let input, button, greeting;
function setup() {
// create canvas
createCanvas(710, 400);
//creates the first value input box
input1 = createInput();
input1.position(20, 65);
//creates the second value input box
input2 = createInput();
input2.position(200, 65);
//creates the 'go' button
go_button = createButton('calculate');
go_button.position(input2.x + input2.width, 65);
//pressing the button triggers the greet() function
go_button.mousePressed(greet);
//creates the reset button
reset_button = createButton('reset');
reset_button.position(20, height - 30);
//immediately hides it
reset_button.hide();
//press the button and reset the screen
reset_button.mousePressed(reset);
//initial text
greeting = createElement('h2', 'what numbers do you want to add?');
greeting.position(20, 5);
textAlign(CENTER);
textSize(50);
}
function greet() {
//hides the inputs and the go button
input1.hide();
input2.hide();
go_button.hide();
//does the math
const total = input1.value() + input2.value();
//updates the text
greeting.html('hello ' + total + '!');
//resets the input values for next time
input1.value('');
input2.value('');
//reveal the reset button
reset_button.show();
//just a thing to show the total
for (let i = 0; i < 200; i++) {
push();
fill(random(255), 255, 255);
translate(random(width), random(height));
rotate(random(2 * PI));
text(total, 0, 0);
pop();
}
}
function reset() {
//hides the old stuff
rect(-1,-1,width+5,height+5);
//shows the inputs and the go button
input1.show();
input2.show();
go_button.show();
//hides the reset button
reset_button.hide();
//updates the text
greeting.html('what numbers do you want to add?');
}

My script for page loading bar, returns differently everytime of F5

I got a free source progress bar, and I wrote a script for it.
the script is here,
var nanobar = new Nanobar( options );
var loaded = 0;
var number_of_media = $("body img").length;
doProgress();
// function for the progress bar
function doProgress() {
$("img").load(function() {
loaded++;
var newWidthPercentage = (loaded / number_of_media) * 100;
nanobar.go(newWidthPercentage);
document.getElementById("showing").innerHTML = newWidthPercentage;
})
};
});
This. I think,
Loaded <-- (which gets + 1 every time an image finished loaded)
divided by
Number of total body images,,
and then multiplied by 100
So that this can make the percentage number of loading process.
Then I put that percentage number into the box of,
A Loading bar's destination point. (which is : nanobar.go( here ))
But the bar moves werid,
everytime I click the menu, it returns different.
so I made a box to display the percentage number ( in the red box you can see in the picture )
I don't understand how this kind of random numbers are coming out every time.
Please advice.
Consider....
6/7 = 0.8571428571;
0.8571428571 * 100 = 85.71428571;
So if you want to 'tidy' these long decimals, then you need to truncate the float. http://www.w3schools.com/jsref/jsref_tofixed.asp
var num = 0.8571428571 * 100;
var n = num.toFixed(2);
Then n == 85.71
I hope this helps.

clear text in html5 canavas strokeText before rendering next

I am using html5 and javascript for rendering a text. I want to update content of text drawn in canvas. I use the following code
var drawArea = document.getElementById('drawingPlane');
var ctx = drawArea.getContext("2d");
ctx.font = "60px Arial";
var counter = 0;
function update() {
counter++;
ctx.strokeText(counter , 50 , 30);
}
setInterval(update , 1000);
The problem is text is not cleared before writing the next value of counter. It is rendering above the previous value of counter. How can I solve this??
Thanks in advance.
You can use the clearRect method to clear the canvas like this:
<script>
var drawArea = document.getElementById('drawingPlane');
var ctx = drawArea.getContext("2d");
ctx.font = "60px Arial";
var counter = 0;
function update() {
ctx.clearRect ( 0 , 0 , drawArea.width, drawArea.height ); // clear canvas
counter++;
ctx.strokeText(counter , 50 , 30);
}
setInterval(update , 1000);
</script>
In HTML5 Canvas shapes (including text) are immediately pixelated (rasterized) and cannot be edited once drawn. The only way to get rid of something you've drawn is clearing the area where it was drawn as suggested by MUG4N. If you want to edit shaped later you need to either use a HTML5 library such as KineticJS which has built a workaround for retaining shapes, or use SVG.

edit jquery-knob counter to display fraction of second

I create time counter using Knob:
$(function($) {
$(".knob").knob({
'fgColor': '#b9e672',
'thickness': 0.3,
'width':150,
'data-min': 0,
'data-max': 30,
'readOnly': true
});
var initval = 30;
$({value: 0}).animate({value: initval},{
duration: 10000,
easing:'swing',
step: function()
{
$('.knob').val(this.value).trigger('change');
}
});
});
I want to display counter in milliseconds, like picture:
how to do this?
thanks,
You can use the step option to chose the step that you would update in your knob value.
There is also another useful thing you can do, that is set the draw function. The draw function determines what gets drawn in the label. By default, it matches the value, but you don't have to.
For instance, if you want to update the knob in milliseconds, but want to round the value to display only the full seconds in the label, you could do something like:
draw: function () { $(this.i).val(Math.round(this.cv)); }
where, accordingly to the comments on the jQuery-knob source, this.cv is the "change value ; not commited value", and this.i the "mixed HTMLInputElement or array of HTMLInputElement"

Animate color change of shape for certain number of frames EaselJs

I am using EaselJS and want to create a flashing color rectangle that will flash a certain number of times when a button is pressed, displaying random colors from an array. It should stop after 10 color flashes and then I want to extract the final color.
So far the relevant code I have is:
var colorArray = ["#FE7B62","#CB2DD3","#F1FD66","#004CE8","#FFD068", "#02A97E"];
square = new createjs.Shape();
square.graphics.beginFill("#000").drawRoundRect(850, 50, 100, 100, 20);
function pushButton(event) {
square.graphics.inject(animateColor);
}
function animateColor(event) {
this.fillStyle = colorArray[parseInt(Math.random()*6)];
}
This code successfully triggers the flashing of colors from my color array, but I am not sure what the best method of running the animation for a limited number of frames is. I tried pausing the ticker and restarting it on the onclick of the button but that failed. I also tried using a for loop in the pushButton function but that caused a "too much recursion error" in the browser. Here is my full file link https://github.com/RMehta95/sherman-land/blob/master/main.js.
I would suggest creating an event to trigger your action (xamountOfFrames). Here is a link to some information that might help
http://www.w3schools.com/tags/ref_eventattributes.asp
I ended up not using the inject function and instead redrawing the shape each time, creating a couple counter and timer variables to ensure that it looped through the proper amount of times.
function pushButton() {
if (timer === false) {
animate = setInterval(animateColor, 200);
timer = true;
}
}
function animateColor() {
square.graphics.clear();
displayColor = colorArray[Math.floor(Math.random()*colorArray.length)];
square.graphics.beginFill(displayColor).drawRoundRect(850, 50, 100, 100, 20);
counter++;
if (counter===15) {
clearInterval(animate);
counter=0;
movePlayer(displayColor);
timer = false;
return;
}
}

Categories

Resources