Javascript draw canvas memory leak - javascript

This script is endlessly taking memory in all the browsers. I can't see why!
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var particles = [], amount = 5;
var x = 100; var y = 100;
var W, H;
var p, gradient;
//dimensions
if(window.innerHeight){
W = window.innerWidth, H = window.innerHeight;
}else{
W = document.documentElement.clientWidth, H = document.documentElement.clientHeight;
}
canvas.width = W, canvas.height = H;
//array voor de meerdere particles
for(var i=0;i<amount;i++){
particles.push(new create_particle());
}
function create_particle(){
//random positie op canvas
this.x = Math.random()*W;
this.y = Math.random()*H;
//random snelheid
this.vx = Math.random()*20-10;
this.vy = Math.random()*20-10;
//Random kleur
var r = Math.random()*255>>0;
var g = Math.random()*255>>0;
var b = Math.random()*255>>0;
this.color = "rgba("+r+", "+g+", "+b+", 0.5)";
this.radius = Math.random()*20+20;
}
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
function draw(){
canvas.width = canvas.width;
canvas.height = canvas.height;
//achtergrond tekenen
//ctx.globalCompositeOperation = "source-over";
//ctx.fillStyle = "rgba(0,0,0,0.5)";
ctx.fillRect(0, 0, W, H);
//ctx.globalCompositeOperation = "lighter";
//teken cirkel
for(var t=0; t<particles.length;t++){
p = particles[t];
//gradient
gradient = ctx.createRadialGradient(p.x,p.y,0,p.x,p.y,p.radius);
gradient.addColorStop(0,"white");
gradient.addColorStop(0.4,"white");
gradient.addColorStop(0.4,p.color);
gradient.addColorStop(1,"black");
ctx.beginPath();
ctx.fillStyle = gradient;
ctx.arc(p.x,p.y,p.radius,Math.PI*2,false)
ctx.fill();
//beweeg
p.x+=p.vx;
p.y+=p.vy;
//canvas boundery detect
if(p.x < -50)p.x = W+50;
if(p.y < -50)p.y=H+50;
if(p.x > W+50)p.x = -50;
if(p.y > H+50)p.y = -50;
}
}
(function animloop(){
canvas.width = canvas.width;
canvas.height = canvas.height;
requestAnimFrame(animloop);
draw();
})();
//resize?
function resizeCanvas(){
canvas.height = W;
canvas.width = H;
ctx.fillRect(0, 0, W, H);
}
if(window.addEventListener){
window.addEventListener('resize', resizeCanvas, false);
}else{
window.attachEvent('resize', resizeCanvas);
}
I tried to change some code around (this is also final version) but still it leaks. If you use this script and watch 'taskmanager' or in-browser's memory check you see that it slowly and constantly eats memory.
EDIT: after adding in the canvas.height solution and moving some declaring's around, the script still leaks! I must say that it looks like Firefox leaks harder then Chrome!

You have:
canvas.width = canvas.width;
canvas.height = canvas.height;
I'm guessing this does the same as clearRect... but to be sure try this too:
function draw(){
ctx.clearRect ( 0 , 0 , canvas.width , canvas.height );
/* draw */
}
See if any thing changes.

Try cleaning the canvas before starting another set of drawing. You can clear it by setting it's width and height again.
Here is some orientative code:
function draw() {
canvas.width = canvas.width;
canvas.height = canvas.height;
/* draw */
}

my guess is your create_particle function could be leaking but im not sure as how, one idea would be to create an interal object instead of using this
function create_particle(){
return {
x: Math.random()*W,
y: Math.random()*H,
vx: Math.random()*20-10,
vy: Math.random()*20-10,
r: Math.random()*255>>0,
g: Math.random()*255>>0,
b: Math.random()*255>>0,
color: "rgba("+r+", "+g+", "+b+", 0.5)",
radius: Math.random()*20+20,
};
}
Im not sure if this is the issue, but it seems to be the only thing I can really think of that kinda looks odd,

Related

Why is the drawn line not clearing from canvas?

Link to JSFiddle for entire code: https://jsfiddle.net/u4mk0gdt/
I read the Mozilla docs on save() and restore() and I thought that "save" saved the current state of the entire canvas and "restore" restored the canvas to the most recent "save" state. Hence I placed the saves and restores in such a way that it should clear the white line that is drawn to canvas after is is drawn. However when I run this code the white line is never cleared from the canvas and is drawn continually without clearing.
ctx.restore();
ctx.save(); // <--should save blank canvas
//DRAW LINE
ctx.moveTo(tMatrix.x1, tMatrix.y1);
ctx.lineTo(w/2,h/2);
ctx.strokeStyle = "white";
ctx.stroke();
ctx.restore(); // <-- should restore to the "save()" above
ctx.save(); // <-- <--should save blank canvas again
As you can see, I made a lot of modifications to your code:
console.log("rotating_recs");
// create canvas and add resize
var canvas, ctx;
function createCanvas() {
canvas = document.createElement("canvas");
canvas.style.position = "absolute";
canvas.style.left = "0px";
canvas.style.top = "0px";
canvas.style.zIndex = 1000;
document.body.appendChild(canvas);
}
function resizeCanvas() {
if (canvas === undefined) {
createCanvas();
}
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx = canvas.getContext("2d");
}
resizeCanvas();
window.addEventListener("resize", resizeCanvas);
var Player = function(x, y, height, width, rot) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.rot = rot;
this.objWinX = 0; //translate the window object and then apply to this
this.objWinY = 0;
this.draw = function() {
//rotate by user.rot degrees, from the players center
ctx.translate(this.x + this.width / 2, this.y + this.height / 2)
ctx.rotate(this.rot * Math.PI / 180)
ctx.translate(-this.x - this.width / 2, -this.y - this.height / 2)
ctx.fillStyle = "grey";
ctx.fillRect(this.x, this.y, this.height, this.width);
ctx.translate(this.x + this.width / 2, this.y + this.height / 2)
ctx.rotate(-this.rot * Math.PI / 180)
ctx.translate(-this.x - this.width / 2, -this.y - this.height / 2)
}
}
var user = new Player(0, 0, 40, 40, 0);
var user2 = new Player(0, 0, 40, 40, 0);
let rot = 0;
function update(time) {
var w, h;
w = canvas.width; // get canvas size incase there has been a resize
h = canvas.height;
ctx.clearRect(0, 0, w, h); // clear the canvas
//MIDDLE RECT
/*
if you don't want this you can just translate by w/2 and h/2, but I would recommend just making the p layers position the middle
*/
user.x = w / 2 - 20;
user.y = h / 2 - 20;
user.rot += 0.5 // or whatever speed
user.draw(); //draw player -- look at the draw function I added some stuff
//LINE
/*
I don't know what you are trying to do, but I just drew the line to the user2's position,
if this doesn't work for your scenario you can change it back
*/
ctx.beginPath()
ctx.moveTo(user2.x + user2.width/2, user2.y + user2.height/2);
ctx.lineTo(w / 2, h / 2);
ctx.strokeStyle = "white";
ctx.stroke();
//FAST SPIN RECT
/*
There are multiple ways to do this, the one that I think you should do, is actually change the position of user two, this uses some very simple trigonometry, if you know this, this is a great way to do this, if not, you can do it how you did previously, and just translate to the center, rotate, and translate back. Similar to what I did with the player draw function. I am going to demonstrate the trig way here:
*/
user2.rot += 5
rot += 2;
user2.x = w/2 + (w/2) * Math.cos(rot * (Math.PI/180))
user2.y = h/2 + (w/2) * Math.sin(rot * (Math.PI/180))
user2.draw();
//RED RECT
ctx.fillStyle = 'red';
ctx.fillRect(140, 60, 40, 40);
requestAnimationFrame(update); // do it all again
}
requestAnimationFrame(update);
While I think you should add some of these modifications into you code, they are not super necessary. To fix you line problem, all you had to do was add ctx.beginPath() before you drew it. The demonstration that I made was not very good (hence demonstration), and you probably shouldn't use it exactly, but definitely look over it. The modified code for you line drawing would look like:
//LINE
ctx.beginPath()
ctx.moveTo(tMatrix.x1, tMatrix.y1);
ctx.lineTo(w/2,h/2);
ctx.strokeStyle = "white";
ctx.stroke();
ctx.restore();
ctx.save();
Hope this helps :D
Sorry for bad spelling

Call tile.draw_tile doesn’t display anything

I am trying to create a small game to learn javascript.Everything works fine except my Rect class.As a matter of fact key_click works fine when it executes some console.log, but doesn’t display anything with tile.draw_tile() (nor gives any error).Could you help me?
var canvas = document.querySelector('canvas');
var c = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let Rect = class {
constructor(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
draw_tile() {
c.fillStyle = "red";
c.fillRect(this.x, this.y, this.width, this.height);
}
}
var mouse = {
x: undefined,
y: undefined,
key_move: window.addEventListener('mousemove',(event)=>{
mouse.x = event.clientX;
mouse.y= event.clientY;
}),
key_click:window.addEventListener('click',(event)=>{
tile.draw_tile();
})
}
let tile = new Rect(mouse.x, mouse.y, 30, 30);
main = function(){
mouse.key_move;
mouse.key_click;
window.requestAnimationFrame(main);
}
window.requestAnimationFrame(main);

for loop not performing with object

I'm using Canvas to play and learn with Javascript. Currently I'm creating a circle and have it display in random areas on the screen. I was able to complete that exercise completely; everything ran smoothly in one function.
Now I would like to create an object for the circle and call it in the for loop. I created the object, but something is still wrong. I'm only seeing one circle instead of 40. I banged my head on this for awhile before coming here for help. Take a look at the code below.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
if (!ctx) {
alert('HTML5 Canvas is not supported in you browser');
}
function Circle(posX, posY, radius, startAngle, endAngle, anticlockwise) {
this.posX = posX;
this.posY = posY;
this.radius = radius;
this.startAngle = startAngle;
this.endAngle = endAngle;
this.anticlockwise = anticlockwise;
this.test = function() {
ctx.beginPath();
ctx.arc(posX, posY, radius, startAngle, endAngle, anticlockwise);
ctx.fill();
}
}
var cir = new Circle(
(Math.random() * canvas.width),
(Math.random() * canvas.height),
20,
0,
Math.PI*2,
true
);
function drawCircle() {
for(var i = 0; i < 40; i++){
cir.test();
}
}
/*setInterval(drawCircle, 400)*/
drawCircle();
You are calling cir.test() 40 times without having 40 instances of Circle. It is the same circle being drawn 40 times on top of itself.
This might be an immediate fix to your problem:
function drawCircle() {
for(var i = 0; i < 40; i++){
// Mind you that doing this
// Will not allow you to reference
// your circles after they are
// created. The best method is
// to put them in an array
// of circles
var cir = new Circle(
(Math.random() * canvas.width),
(Math.random() * canvas.height),
20,
0,
Math.PI*2,
true
);
cir.test();
}
}
/*setInterval(drawCircle, 400)*/
drawCircle();
However, I would recommend the following changes to your code:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
if (!ctx) {
alert('HTML5 Canvas is not supported in you browser');
}
function Circle(posX, posY, radius, startAngle, endAngle, anticlockwise) {
this.posX = posX;
this.posY = posY;
this.radius = radius;
this.startAngle = startAngle;
this.endAngle = endAngle;
this.anticlockwise = anticlockwise;
// Using better function names
// is always a good idea
this.testDraw = function() {
ctx.beginPath();
ctx.arc(posX, posY, radius, startAngle, endAngle, anticlockwise);
ctx.fill();
}
}
// Create an array to fill
// with Circle instances
var circlesArray = []
// Changed drawCircle to drawCircles
// it is clearer
function drawCircles() {
for(var i = 0; i < 40; i++){
// Create new Circle objects
// and add them to the circlesArray
// this will allow you to have a
// each circle later on
circlesArray.push(new Circle(
(Math.random() * canvas.width),
(Math.random() * canvas.height),
20,
0,
Math.PI*2,
true
));
// Go through each item of the array
// and call the test function
circlesArray[i].testDraw();
}
}
/*setInterval(drawCircle, 400)*/
drawCircles();
Currently your drawCircle() function is running a single test function on the same 'cir' variable 40 times. What you want to do is to fill an array with 40 new items using the for-loop. Then, use another for-loop to define those items as new Circle objects and call the test function on each new circle.
Here is the code I would use:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
if (!ctx) {
alert('HTML5 Canvas is not supported in you browser');
}
function Circle(posX, posY, radius, startAngle, endAngle, anticlockwise) {
this.posX = posX;
this.posY = posY;
this.radius = radius;
this.startAngle = startAngle;
this.endAngle = endAngle;
this.anticlockwise = anticlockwise;
this.test = function() {
ctx.beginPath();
ctx.arc(posX, posY, radius, startAngle, endAngle, anticlockwise);
ctx.fill();
}
}
/*Create an array to hold your circles*/
var circleArray = [];
function drawCircle() {
for (var i = 0; i < 40; i++) {
circleArray.push('cirlce' + i); /*Push circle variable into circleArray*/
}
for (var i = 0; i < circleArray.length; i++) {
/*Create a new circle object for every iteration of the circleArray*/
circleArray[i] = new Circle(
(Math.random() * canvas.width), (Math.random() * canvas.height),
20,
0,
Math.PI * 2,
true
);
circleArray[i].test(); /*Run the test function for every item in the circle array*/
}
}
/*setInterval(drawCircle, 400)*/
drawCircle();
<canvas id='canvas'></canvas>
Please read the comments, if you need more help understanding this just comment below.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
if (!ctx) {
alert('HTML5 Canvas is not supported in you browser');
}
//The only thing I can see perhaps changing is radius so use radius as parameter
function Circle(radius) {
this.posX = Math.random() * canvas.width; //This is always going to be the same so no need to pass as an argument
this.posY = Math.random() * canvas.height; //So will this
this.test = function() {
ctx.beginPath();
ctx.arc(this.posX, this.posY, radius, 0, Math.PI*2, true); //So will Math.PI*2, and true
ctx.fill();
}
this.test();
}
function drawCircle() {
for(var i = 0; i < 40; i++){
new Circle(i); //This passes i as the radius so you can see the differences
}
}
drawCircle();

HTML5 Canvas scaling an image animation

I've created a straight forward linear HTML5 animation but I now want the image to continuously scale bigger then smaller until the end of the canvas' height.
What's the best way to do this?
Here's a JSFIDDLE
window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.oRequestAnimationFrame;
var canvas = document.getElementById('monopoly-piece');
var context = canvas.getContext('2d');
var img = document.createElement("img");
img.src = "images/tophat.png";
img.shadowBlur = 15;
img.shadowColor = "rgb(0, 0, 0)";
var xSpeed = 0; //px per ms
var ySpeed = 0.15;
function animate(nowTime, lastTime, xPos, yPos) {
// update
if ((img.style.height + yPos) > canvas.height) {
xPos = 0;
yPos = 0;
}
var timeDelta = nowTime - lastTime;
var xDelta = xSpeed * timeDelta;
var yDelta = ySpeed * timeDelta;
// clear
context.clearRect(0, 0, canvas.width, canvas.height);
// shadow
context.shadowOffsetX = 3;
context.shadowOffsetY = 7;
context.shadowBlur = 4;
context.shadowColor = 'rgba(0, 0, 0, 0.4)';
//draw img
context.drawImage(img, xPos, yPos);
if (yPos > canvas.height - img.height ) {
addMarker();
}
else {
requestAnimationFrame(
function(timestamp){
animate(timestamp, nowTime, xPos + xDelta, yPos + yDelta);
}
);
}
}
animate(0, 0, -10, 0);
Here is my current code which animates an image from the top of the canvas element to the bottom and then stops.
Thanks.
context.DrawImage has additional parameters that let you scale your image to your needs:
// var scale is the scaling factor to apply between 0.00 and 1.00
// scale=0.50 will draw the image half-sized
var scale=0.50;
// var y is the top position on the canvas where you want to drawImage your image
var y=0;
context.drawImage(
// draw img
img,
// clip a rectangular portion from img
// starting at [top,left]=[0,0]
// and with width,height == img.width,img.height
0, 0, img.width, img.height,
// draw that clipped portion of of img on the canvas
// at [top,left]=[0,y]
// with width scaled to img.width*scale
// and height scaled to img.height*scale
0, y, img.width*scale, img.height*scale
)
Here's an example you can start with and fit to your own design needs:
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cw = canvas.width;
var ch = canvas.height;
var scale = 1;
var scaleDirection = 1
var iw, ih;
var y = 1;
var yIncrement = ch / 200;
var img = new Image();
img.onload = start;
img.src = "https://dl.dropboxusercontent.com/u/139992952/multple/sun.png";
function start() {
iw = img.width;
ih = img.height;
requestAnimationFrame(animate);
}
function animate(time) {
if (scale > 0) {
requestAnimationFrame(animate);
}
ctx.clearRect(0, 0, cw, ch);
ctx.drawImage(img, 0, 0, iw, ih, 0, y, iw * scale / 100, ih * scale / 100);
scale += scaleDirection;
if (scale > 100) {
scale = 100;
scaleDirection *= -1;
}
y += yIncrement;
}
$("#test").click(function() {
scale = y = scaleDirection = 1;
requestAnimationFrame(animate);
});
body{ background-color: ivory; }
canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id="test">Animate Again</button>
<br>
<canvas id="canvas" width=80 height=250></canvas>

Animating game using requestAnimationFrame

I tried to make some simply game using requestAnimFrame but animation doesn't work and I don't know why. Maybe some one can help? Here is the code:
// requestAnimationFrame() shim by Paul Irish
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
window.setTimeout(callback, 1000 / 60);
};
})();
//Create canvas
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 640;
canvas.height = 480;
document.body.appendChild(canvas);
// The main game loop
var lastTime;
function main() {
var now = Date.now();
var dt = now - lastTime;
draw();
update(dt);
lastTime = now;
requestAnimFrame(main);
}
main();
function ball(){
this.radius = 5;
this.x = 300;
this.y = 50;
this.vx = 200;
this.vy = 200;
this.ax = 0;
this.ay = 0;
this.color = "red";
this.draw = function(){
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.arc( this.x, this.y, this.radius, 0, 2 * Math.PI );
ctx.fill();
};
}
function draw() {
newBall = new ball();
newBall.draw();
}
function update(dt) {
newBall = new ball();
newBall.x += newBall.vx * dt;
}
In update(dt) function ball dosen't move and I don't know why...
There are several errors in your code:
You're initializing variables outside of a function, always use an initializer (immediately invoked function) for that.
As mentioned by kalley you are creating a new ball at the starting position for every draw instead of using a global object.
Even if your ball would draw correctly it would be outside the drawing area within the next frame because Date.now() is measured in seconds (use .getMilliseconds()).
Lastly the ball stays at the same position because the canvas isn't cleaned up after each draw.
what you're looking for:
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
theBall.draw();
}
There are several other things but this fiddle should do for now.

Categories