The Image is flickering as I continuously push the button. The problem might be in ctx.clearRect(0,0,100,500) . How can I resolve the problem?
I am trying to animate in HTML 5 canvas.
I need a moving object in canvas and when I push the button, the other moving object follow the previous without flickering.
function draw(x,y){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.save();
ctx.clearRect(0,0,100,500); // This may be the problem
var img=document.getElementById("Image");
ctx.drawImage(img,50,y);
ctx.restore();
y -= 10;
var loopTimer = setTimeout('draw('+x+','+y+')',50);
}
HTML 5
<button onclick="draw(0,500)">Draw</button>
<canvas id="canvas" width="600" height="500">
</canvas>
It looks like the problem may be because you aren't clearing the entire canvas. Try this:
function draw(x,y){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.save();
ctx.clearRect(0,0, canvas.width, canvas.height);
var img=document.getElementById("Image");
ctx.drawImage(img,50,y);
ctx.restore();
y -= 10;
var loopTimer = setTimeout('draw('+x+','+y+')',50);
}
Demo
The image flicker when you press the button more than once, which means you start the setTimeout() more than once. Add a variable to check if it's already been pressed.
Related
I want to change the line width in canvas from 5 to 10 from a click event but it's not working in JavaScript
function draw(e) {
if (!painting) {
return;
}
exitdraw(e);
c.lineWidth = 5;
c.lineTo(e.clientX, e.clientY);
c.lineCap = 'round';
c.strokeStyle = 'aqua';
c.stroke();
c.beginPath();
c.moveTo(e.clientX, e.clientY);
}
//this is the listener i want to change the linewidth
var canvas = document.querySelector('#canvas');
var btn = document.getElementById('button');
btn.addEventListener('click',function(){
canvas.getContext('2d').lineWidth = 10;
})
<button onclick="changeWidth()">Change Width</button>
<br />
<canvas height="150" id="canvas" width="200"></canvas>
<script>
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var lineWidth = 5;
function draw() {
ctx.beginPath();
ctx.lineWidth = lineWidth;
ctx.arc(100, 75, 32, 0, 2 * Math.PI);
ctx.stroke();
}
draw();
function changeWidth() {
lineWidth = 10;
draw();
}
</script>
Canvas doesn't store references to what you draw on it so it's impossible to change property that will affect what you draw.
What I mean is in order to change some drawing in your canvas you should render it again with your new style.
Because you use client data on your draw function you should store the data (clientX/Y etc...) in variables (or you may prefer one object that stores all data) and call that function again, but you need to refactor your function to get lineWidth as a param.
Trouble is, you are changing the value after content is drawn. For changes to take affect, you may want to redraw the content after a change. Like:
btn.addEventListener('click',function(){
canvas.getContext('2d').lineWidth = 10;
draw(); // apply changes by redrawing
})
And of course you should omit the c.lineWidth = 5 line from draw function to not to override change. Perhaps do c.lineWidth = 5 in a initializer function ot smt as a default value.
thanks you all for help but i solved it just saved the value in variable and manipulate it like #Whatatimetobealive said
Ok, I've noticed this bug happen not only in the following code(which is just to illustrate), but every code I've written for canvas;
basically, in chrome(I didn't test other browsers),
once you shift your current tab to either a different pc screen, or simply if you have a few tabs in a row and decide to make a new window out of your current tab,
the canvas itself fails to draw. it is stuck and no reason is given in the console.
Here is a GIF of it happening:
http://gifmaker.cc/PlayGIFAnimation.php?folder=2016081601ZEuvXaZnxC2T9fHNNqSW3l&file=output_f72O1H.gif
Just a simple canvas code if you want to try it out:
<canvas id="canvas" width="500" height="400" style="border:1px solid #000000;"></canvas>
<script>
// grab the canvas and context
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// inital coordinates of the black square
var x = 0;
var y = 200;
// speed of the movement in x- and y-direction
// actual no movement in y-direction
var vX = 1;
var vY = 0;
// width and height of the square
var width = 10;
var height = 10;
function animate() {
// clear
// comment this clear function to see the plot of the sine movement
ctx.clearRect(0, 0, canvas.width, canvas.height);
x += vX;
y += vY;
// if the block leaves the canvas on the right side
// bring it back to the left side
if(x>500) {
x = 0;
}
ctx.fillRect(x, y, width, height);
setTimeout(animate, 33);
}
// call the animate function manually for the first time
animate();
</script>
Some sites fixed this bug but I don't know if I am allowed to link them here.
Hey Im experimenting with some html5 animation and so far I have a square that "falls" whenever I press the button. I was wondering how i could have it go back to the top when it hits the bottom and fall again.
My current code is:
<html>
<head>
</head>
<body>
<canvas id="myCanvas" width="200" height="400" style="border:1px solid black;">
Your browser does not support the HTML5 canvas tag.
</canvas>
<script>
function draw (x,y){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.save();
var side = 10
var up = 10
ctx.clearRect(0,0,200,400);
ctx.fillStyle = "#FF0000";
ctx.fillRect(x,y,up,side);
ctx.restore();
y += 5;
var loopTimer = setTimeout('draw('+x+','+y+')',30);
}
</script>
<button onclick="draw(0,0)">draw</button>
</body>
</html>
Using your variables y, you can simply check if it is below the height of the canvas height.
if( y > c.height ){ // use the canvas height, not the context height
y = 0;
}
Also, the way you're currently calling the timer is a bit inefficient. Instead of :
var loopTimer = setTimeout('draw('+x+','+y+')',30);
I would recommend
var loopTimer = setTimeout(function(){ draw(x,y); },30);
Here's a working example: http://jsfiddle.net/vwcdpLvv/
Just giving canvas a go for the first time with the intention of creating a game. I have an image displaying but oddly the fillStyle method doesn't seem to be working. ( At least the canvas background is still white in google chrome.)
Note that in my code the canvas var is actually the canvas elements 2d context, maybe that's where i'm getting myself confused? i can't see the problem, would appreciate if anyone else could.
LD24.js:
const FPS = 30;
var canvasWidth = 0;
var canvasHeight = 0;
var xPos = 0;
var yPos = 0;
var smiley = new Image();
smiley.src = "http://javascript-tutorials.googlecode.com/files/jsplatformer1-smiley.jpg";
var canvas = null;
window.onload = init; //set init function to be called onload
function init(){
canvasWidth = document.getElementById('canvas').width;
canvasHeight = document.getElementById('canvas').height;
canvas = document.getElementById('canvas').getContext('2d');
setInterval(function(){
update();
draw();
}, 1000/FPS);
}
function update(){
}
function draw()
{
canvas.clearRect(0,0,canvasWidth,canvasHeight);
canvas.fillStyle = "#FFAA33"; //orange fill
canvas.drawImage(smiley, xPos, yPos);
}
LD24.html:
<html>
<head>
<script language="javascript" type="text/javascript" src="LD24.js"></script>
</head>
<body>
<canvas id="canvas" width="800" height="600">
<p> Your browser does not support the canvas element needed to play this game :(</p>
</canvas>
</body>
</html>
3 notes:
fillStyle does not cause your canvas to be filled. It means that when you fill a shape it will be filled with that color. Therefore you need to write canvas.fillRect( xPos, yPos, width, height).
Wait until your image actually loads, otherwise the rendering may be inconsistent or buggy.
Careful of cross-domain images used in your canvas - most browsers will throw a security exception and stop executing your code.
Wait till image loads as well:
var img = new Image();
img.onload = function() {
handleLoadedTexture(img);
};
img.src = "image.png";
function handleLoadedTexture(img) {
//call loop etc that uses image
};
Or maybe you were just missing
canvas.fill();
after
canvas.drawImage(smiley, xPos, yPos);
I have created a basic shape in HTML canvas element which works fine.
The problem occurs when I resize the canvas, all the drawing in the canvas disappears. Is this the normal behavior? or is there a function that can be used to stop this?
One way to fix this could be to call drawing function again on canvas resize however this may not be very efficient if there is huge content to be drawn.
What's the best way?
Here is the link to sample code https://gist.github.com/2983915
You need to redraw the scene when you resize.
setting the width or height of a canvas, even if you are setting it to the same value as before, not only clears the canvas but resets the entire canvas context. Any set properties (fillStyle, lineWidth, the clipping region, etc) will also be reset.
If you do not have the ability to redraw the scene from whatever data structures you might have representing the canvas, you can always save the entire canvas itself by drawing it to an in-memory canvas, setting the original width, and drawing the in-memory canvas back to the original canvas.
Here's a really quick example of saving the canvas bitmap and putting it back after a resize:
http://jsfiddle.net/simonsarris/weMbr/
Everytime you resize the canvas it will reset itself to transparant black, as defined in the spec.
You will either have to:
redraw when you resize the canvas, or,
don't resize the canvas
One another way is to use the debounce if you are concerned with the performance.
It doesnt resize or redraw every position you are dragging. But it will resize only when the it is resized.
// Assume canvas is in scope
addEventListener.("resize", debouncedResize );
// debounce timeout handle
var debounceTimeoutHandle;
// The debounce time in ms (1/1000th second)
const DEBOUNCE_TIME = 100;
// Resize function
function debouncedResize () {
clearTimeout(debounceTimeoutHandle); // Clears any pending debounce events
// Schedule a canvas resize
debounceTimeoutHandle = setTimeout(resizeCanvas, DEBOUNCE_TIME);
}
// canvas resize function
function resizeCanvas () { ... resize and redraw ... }
I had the same problem. Try following code
var wrapper = document.getElementById("signature-pad");
var canvas = wrapper.querySelector("canvas");
var ratio = Math.max(window.devicePixelRatio || 1, 1);
canvas.width = canvas.offsetWidth * ratio;
canvas.height = canvas.offsetHeight * ratio;
It keeps the drawing as it is
One thing that worked for me was to use requestAnimationFrame().
let height = window.innerHeight;
let width = window.innerWidth;
function handleWindowResize() {
height = window.innerHeight;
width = window.innerWidth;
}
function render() {
// Draw your fun shapes here
// ...
// Keep this on the bottom
requestAnimationFrame(render);
}
// Canvas being defined at the top of the file.
function init() {
ctx = canvas.getContext("2d");
render();
}
I had the same problem when I had to resize the canvas to adjust it to the screen.
But I solved it with this code:
var c = document.getElementById('canvas');
ctx = c.getContext('2d');
ctx.fillRect(0,0,20,20);
// Save canvas settings
ctx.save();
// Save canvas context
var dataURL = c.toDataURL('image/jpeg');
// Resize canvas
c.width = 50;
c.height = 50;
// Restore canvas context
var img = document.createElement('img');
img.src = dataURL;
img.onload=function(){
ctx.drawImage(img,20,20);
}
// Restote canvas settings
ctx.restore();
<canvas id=canvas width=40 height=40></canvas>
I also met this problem.but after a experiment, I found that Resizing the canvas element will automatically clear all drawings off the canvas!
just try the code below
<canvas id = 'canvas'></canvas>
<script>
var canvas1 = document.getElementById('canvas')
console.log('canvas size',canvas1.width, canvas1.height)
var ctx = canvas1.getContext('2d')
ctx.font = 'Bold 48px Arial'
var f = ctx.font
canvas1.width = 480
var f1 = ctx.font
alert(f === f1) //false
</script>