setTimeout with canvas - javascript

I am trying to run an animate background with canvas. Right now the setTimeout shows an error in chrome Uncaught SyntaxError: Unexpected identifier. I must be animating it wrong.
When I remove setTimeout and just have the tiles(), everything works fine (i.e. not animated, but show the correct background that I want). So I am sure, it has something to do with setTimeout.
Anyone got clues for me?
function createBackground(){
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d'),
background = $('#game .background')[0],
rect = background.getBoundingClientRect(), //returns the dimension of background
gradient,
m = monster.settings.monsterSize;
canvas.width = rect.width;
canvas.height = rect.height;
/* create checker */
tile_cols = canvas.width / m;
tile_rows = canvas.height / m;
setTimeout(tiles(ctx, m, tile_cols, tile_rows), 300);
/* add canvas to html element */
background.appendChild(canvas);
}
function tiles(ctx, m, tile_cols, tile_rows){
for (var i=0; i<tile_cols; i++){
for (var j=0; j<tile_rows; j++){
var x = Math.ceil(Math.random()*3);
switch(x){
case 1:
ctx.fillStyle = 'black';
break;
....
case 3:
ctx.fillStyle = '#00080E';
break;
}
ctx.strokeStyle = 'black';
ctx.beginPath();
...
ctx.closePath();
ctx.fill();
ctx.stroke();
};
};
return this;
}

You're assigning the result of tiles(ctx, m, tile_cols, tile_rows) to the first parameter of setTimeout
Change it to
setTimeout(function() {
tiles(ctx, m, tile_cols, tile_rows)
}, 300);
You should have a look at requestAnimationFrame for this task. Paul Irish wrote a good article about it.

Related

Why does my triangle on canvas have artifacts? [duplicate]

I'm doing a Pong game in javascript in order to learn making games, and I want to make it object oriented.
I can't get clearRect to work. All it does is draw a line that grows longer.
Here is the relevant code:
function Ball(){
this.radius = 5;
this.Y = 20;
this.X = 25;
this.draw = function() {
ctx.arc(this.X, this.Y, this.radius, 0, Math.PI*2, true);
ctx.fillStyle = '#00ff00';
ctx.fill();
};
}
var ball = new Ball();
function draw(){
player.draw();
ball.draw();
}
function update(){
ctx.clearRect(0, 0, 800, 400);
draw();
ball.X++;
}
I've tried to put the ctx.clearRect part in the draw() and ball.draw() functions and it doesn't work.
I also tried fillRect with white but it gives the same results.
How can I fix this?
Your real problem is you are not closing your circle's path.
Add ctx.beginPath() before you draw the circle.
jsFiddle.
Also, some tips...
Your assets should not be responsible for drawing themselves (their draw() method). Instead, perhaps define their visual properties (is it a circle? radius?) and let your main render function handle canvas specific drawing (this also has the advantage that you can switch your renderer to regular DOM elements or WebGL further down the track easily).
Instead of setInterval(), use requestAnimationFrame(). Support is not that great at the moment so you may want to shim its functionality with setInterval() or the recursive setTimeout() pattern.
Your clearRect() should be passed the dimensions from the canvas element (or have them defined somewhere). Including them in your rendering functions is akin to magic numbers and could lead to a maintenance issue further down the track.
window.onload = function() {
var cvs = document.getElementById('canvas');
var ctx = cvs.getContext('2d');
var cvsW = cvs.Width;
var cvsH = cvs.Height;
var snakeW = 10;
var snakeH = 10;
function drawSnake(x, y) {
ctx.fillStyle = '#FFF';
ctx.fillRect(x*snakeW, y * snakeH, snakeW, snakeH);
ctx.fillStyle = '#000';
ctx.strokeRect(x*snakeW, y * snakeH, snakeW, snakeH);
}
// drawSnake(4, 5)
//create our snake object, it will contain 4 cells in default
var len = 4;
var snake = [];
for(var i = len -1; i >=0; i--) {
snake.push(
{
x: i,
y: 0
}
)
};
function draw() {
ctx.clearRect(0, 0, cvsW, cvsH)
for(var i = 0; i < snake.length; i++) {
var x = snake[i].x;
var y = snake[i].y;
drawSnake(x, y)
}
//snake head
var snakeX = snake[0].x;
var snakeY = snake[0].y;
//remove to last entry (the snake Tail);
snake.pop();
// //create a new head, based on the previous head and the direction;
snakeX++;
let newHead = {
x: snakeX,
y: snakeY
}
snake.unshift(newHead)
}
setInterval(draw, 60);
}
my clearRect is not working, what's the problem and solution?

Canvas strokeStyle not changing in internet explorer

I'm trying to get a webpage screen saver working on windows 10, but it's using internet explorer :(
I want the color of a line to fade into the next color while being drawn. This works fine in Chrome, but in internet explorer the strokeStyle doesn't update on every step.
I've included a link to a snippet showing the issue:
function colorTween(from, to, step, maxStep) {
const newColor = [0,0,0,0];
from.forEach(function (fromVal, i) {
const toVal = to[i];
newColor[i] = fromVal + (((toVal - fromVal)/maxStep)*step);
});
return newColor;
}
//init
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.lineWidth = 50;
ctx.lineCap = "round";
const fromColor = [0,0,0,1]; //black
const toColor = [255,255,255,1]; //white
const y = canvas.height/2;
let x = 0;
let prevX = 0;
//draw loop
setInterval(function () {
//increase x
x++;
//get color fading into next color
const drawColor = colorTween(fromColor, toColor, x, canvas.width);
//draw line segment
ctx.strokeStyle = "rgba("+drawColor[0]+","+drawColor[1]+","+drawColor[2]+","+drawColor[3]+")";
ctx.beginPath();
ctx.moveTo(prevX, y);
ctx.lineTo(x, y);
ctx.stroke();
ctx.closePath();
//setup for next loop
prevX = x;
}, 1000/60);
body, canvas {
margin: 0;
padding: 0;
border: none;
overflow: none;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
</html>
Internet Explorer did choke on too decimal numbers in RGB CSS values (strokeStyle is parsed as a CSS <color> value).
Your colorTween function will very likely produce such decimal numbers and IE will just ignore the value entirely.
To avoid that, round your R, G, and B values, and while I'm not sure it's needed, you may want to also call .toFixed() on the Alpha value (for R,G,B the decimal is anyway discarded by implementations, and for alpha the maximum granularity is 1/256, i.e ~0.004).
from.forEach(function (fromVal, i) {
const toVal = to[i];
const newVal = fromVal + (((toVal - fromVal)/maxStep)*step);
newColor[i] = i===3 ? newVal.toFixed(3) : Math.round(newVal);

Erasing only paticular element of canvas in JS

I want to create something like scratch card.
I created a canvas and added text to it.I than added a box over the text to hide it.Finally write down the code to erase(scratch) that box.
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50);
ctx.globalCompositeOperation = 'source-over';
ctx.fillStyle='red';
ctx.fillRect(0,0,500,500);
function myFunction(event) {
var x = event.touches[0].clientX;
var y = event.touches[0].clientY;
document.getElementById("demo").innerHTML = x + ", " + y;
ctx.globalCompositeOperation = 'destination-out';
ctx.arc(x,y,30,0,2*Math.PI);
ctx.fill();
}
But the problem is it delete the text also.
How could I only delete that box not the text?
Canvas context keeps only one drawing state, which is the one rendered. If you modify a pixel, it won't remember how it was before, and since it has no built-in concept of layers, when you clear a pixel, it's just a transparent pixel.
So to achieve what you want, the easiest is to build this layering logic yourself, e.g by creating two "off-screen" canvases, as in "not appended in the DOM", one for the scratchable area, and one for the background that should be revealed.
Then on a third canvas, you'll draw both canvases every time. It is this third canvas that will be presented to your user:
var canvas = document.getElementById("myCanvas");
// the context that will be presented to the user
var main = canvas.getContext("2d");
// an offscreen one that will hold the background
var background = canvas.cloneNode().getContext("2d");
// and the one we will scratch
var scratch = canvas.cloneNode().getContext("2d");
generateBackground();
generateScratch();
drawAll();
// the events handlers
var down = false;
canvas.onmousemove = handlemousemove;
canvas.onmousedown = handlemousedown;
canvas.onmouseup = handlemouseup;
function drawAll() {
main.clearRect(0,0,canvas.width,canvas.height);
main.drawImage(background.canvas, 0,0);
main.drawImage(scratch.canvas, 0,0);
}
function generateBackground(){
background.font = "30px Arial";
background.fillText("Hello World",10,50);
}
function generateScratch() {
scratch.fillStyle='red';
scratch.fillRect(0,0,500,500);
scratch.globalCompositeOperation = 'destination-out';
}
function handlemousedown(evt) {
down = true;
handlemousemove(evt);
}
function handlemouseup(evt) {
down = false;
}
function handlemousemove(evt) {
if(!down) return;
var x = evt.clientX - canvas.offsetLeft;
var y = evt.clientY - canvas.offsetTop;
scratch.beginPath();
scratch.arc(x, y, 30, 0, 2*Math.PI);
scratch.fill();
drawAll();
}
<canvas id="myCanvas"></canvas>
Now, it could all have been done on the same canvas, but performance wise, it's probably not the best, since it implies generating an overly complex sub-path that should get re-rendered at every draw, also, it is not much easier to implement:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext('2d');
ctx.font = '30px Arial';
drawAll();
// the events handlers
var down = false;
canvas.onmousemove = handlemousemove;
canvas.onmousedown = handlemousedown;
canvas.onmouseup = handlemouseup;
function drawAll() {
ctx.globalCompositeOperation = 'source-over';
// first draw the scratch pad, intact
ctx.fillStyle = 'red';
ctx.fillRect(0,0,500,500);
// then erase with the currently being defined path
// see 'handlemousemove's note
ctx.globalCompositeOperation = 'destination-out';
ctx.fill();
// finally draw the text behind
ctx.globalCompositeOperation = 'destination-over';
ctx.fillStyle = 'black';
ctx.fillText("Hello World",10,50);
}
function handlemousedown(evt) {
down = true;
handlemousemove(evt);
}
function handlemouseup(evt) {
down = false;
}
function handlemousemove(evt) {
if(!down) return;
var x = evt.clientX - canvas.offsetLeft;
var y = evt.clientY - canvas.offsetTop;
// note how here we don't create a new Path,
// meaning that all the arcs are being added to the single one being rendered
ctx.moveTo(x, y);
ctx.arc(x, y, 30, 0, 2*Math.PI);
drawAll();
}
<canvas id="myCanvas"></canvas>
How could I only delete that box not the text?
You can't, you'll have to redraw the text. Once you've drawn the box over the text, you've obliterated it, it doesn't exist anymore. Canvas is pixel-based, not shape-based like SVG.

Canvas Javascript Looping

I'm trying to loop my animation, but no matter what I do, it won't loop. I'm pretty new to canvas, javascript and code in general.
var canvas = document.getElementById("fabrication");
var ctx = canvas.getContext("2d");
var background = new Image();
background.src =
"C:/Users/dylan/Desktop/ProjectTwo/Images/fabricationbackground.jpg";
background.onload = function(){
}
//Loading all of my canvas
var posi =[];
posi[1] = 20;
posi[2] = 20;
var dx=10;
var dy=10;
var ballRadius = 4;
//Variables for drawing a ball and it's movement
function drawballleft(){
posi =xy(posi[1],posi[2])
}
function xy(x,y){
ctx.drawImage(background,0,0);
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = "#FFFFFFF";
ctx.fill();
ctx.closePath();
var newpos=[];
newpos[1]= x +dx;
newpos[2]= y +dy;
return newpos;
//Drawing the ball, making it move off canvas.
if (newpos[1] > canvas.width) {
newpos[1] = 20;
}
if (newpos[2] > canvas.height) {
newpos[2] = 20;
}
//If statement to detect if the ball moves off the canvas, to make it return to original spot
}
setInterval(drawballleft, 20);
//Looping the function
Please let me know if I've done something wrong, I really want to learn what I'm doing here. The ball is supposed to go off the canvas, and loop back onto itself, but it goes off the canvas and ends.
Thanks in advance!
I have made a few changes to your code.
First I am using requestAnimationFrame instead of setInterval. http://www.javascriptkit.com/javatutors/requestanimationframe.shtml
Second I am not using an image because I didn't want to run into a CORS issue. But you can put your background image back.
I simplified your posi array to use indexes 0 and 1 instead of 1 and 2 to clean up how you create your array.
I moved your return from before the two ifs to after so the ball will move back to the left or top when it goes off the side. I think that was the real problem you were seeing
var canvas = document.getElementById("fabrication");
var ctx = canvas.getContext("2d");
//Loading all of my canvas
var posi =[20,20];
var dx=10;
var dy=10;
var ballRadius = 4;
//Variables for drawing a ball and it's movement
function drawballleft(){
posi = xy(posi[0],posi[1])
requestAnimationFrame(drawballleft);
}
function xy(x,y){
ctx.fillStyle = '#FFF';
ctx.fillRect(0,0,400,300);
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = "#000";
ctx.fill();
ctx.closePath();
var newpos=[x+dx,y+dy];
//Drawing the ball, making it move off canvas.
if (newpos[0] > canvas.width) {
newpos[0] = 20;
}
if (newpos[1] > canvas.height) {
newpos[1] = 20;
}
//If statement to detect if the ball moves off the canvas, to make it return to original spot
return newpos;
}
requestAnimationFrame(drawballleft);
canvas {
outline: 1px solid red;
}
<canvas width="400" height="300" id="fabrication"></canvas>
To make it all even simpler...
Use an external script for handling the canvas.
A really good one ;) :
https://github.com/GustavGenberg/handy-front-end#canvasjs
Include it with
<script type="text/javascript" src="https://gustavgenberg.github.io/handy-front-end/Canvas.js"></script>
Then it's this simple:
// Setup canvas
const canvas = new Canvas('my-canvas', 400, 300).start(function (ctx, handyObject, now) {
// init
handyObject.Ball = {};
handyObject.Ball.position = { x: 20, y: 20 };
handyObject.Ball.dx = 10;
handyObject.Ball.dy = 10;
handyObject.Ball.ballRadius = 4;
});
// Update loop, runs before draw loop
canvas.on('update', function (handyObject, delta, now) {
handyObject.Ball.position.x += handyObject.Ball.dx;
handyObject.Ball.position.y += handyObject.Ball.dy;
if(handyObject.Ball.position.x > canvas.width)
handyObject.Ball.position.x = 20;
if(handyObject.Ball.position.y > canvas.height)
handyObject.Ball.position.y = 20;
});
// Draw loop
canvas.on('draw', function (ctx, handyObject, delta, now) {
ctx.clear();
ctx.beginPath();
ctx.arc(handyObject.Ball.position.x, handyObject.Ball.position.y, handyObject.Ball.ballRadius, 0, Math.PI * 2);
ctx.fillStyle = '#000';
ctx.fill();
ctx.closePath();
});
I restructured your code and used the external script, and now it looks much cleaner and easier to read and toubleshoot!
JSFiddle: https://jsfiddle.net/n7osvt7y/

Is there a way to streamline canvas code

This is a bit of a strange issue but I have a world map that is produced from lines of canvas code.
The canvas code is derived from an SVG file that was automatically converted by a website but it produced 47000 lines of code & a 1.5mb file size.
This obviously takes some time to load and occasionally it doesn't appear (it currently resides in a .js file that is remote loaded).
Is there a way to streamline this code to reduce the file size.
I have thought about transferring all the line coordinates into a sql table and producing it that way but I'm not sure if that would be any better.
Example code:
function world(scale) {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.scale(scale,scale);
ctx.save();
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(39960,0);
ctx.lineTo(39960,19980);
ctx.lineTo(0,19980);
ctx.closePath();
ctx.clip();
ctx.strokeStyle = "#ffffff";
ctx.lineCap = "butt";
ctx.lineJoin = "miter";
ctx.miterLimit = 4;
ctx.save();
ctx.restore();
ctx.save();
ctx.restore();
ctx.save();
ctx.save();
ctx.fillStyle = "#bcbcbc";
ctx.strokeStyle = "#ffffff";
ctx.lineWidth = 5.5;
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.miterLimit = 4;
ctx.beginPath();
ctx.moveTo(14553,0);
ctx.lineTo(14528,2);
ctx.lineTo(14502,2);
ctx.lineTo(14476,2);
ctx.lineTo(14448,4);
ctx.lineTo(14464,17);
ctx.lineTo(14436,15);
ctx.lineTo(14413,11);
ctx.lineTo(14395,4);
function CanvasProxy(target){
var Host=new Object;
for (var v in target)
switch (typeof target[v]) {
case "function":Host[v]=addMethod.bind(v);break;
case "number":setProperty(v);break;
case "string":setProperty(v);break;
case "object":Host[v]=target[v];break;
default:setSimpleProperty(v)
};
return Host;
function addMethod(){
var ret=target[this].apply(target,arguments);
if (typeof ret==="undefined") return Host;
Host[this]=target[this];
return ret;
}
function setProperty(p){
function property(v){target[p]=v;return Host;}
property.toString=property.valueOf=function(){return target[p]}
Object.defineProperty(Host, p , {get : function(){return property}, set : function(v){ target[p] = v}});
}
function setSimpleProperty(p){
Object.defineProperty(Host, p , {get : function(){return target[p]}, set : function(v){ target[p] = v}});
}
}
var ctx;
function _init(){
var canvas = document.getElementById("myCanvas");
ctx = CanvasProxy(canvas.getContext("2d"));
}
function world(scale) {
ctx.scale(scale,scale)
.save()
.beginPath()
.moveTo(0,0)
.lineTo(39960,0)
.lineTo(39960,19980)
.lineTo(0,19980)
.closePath()
.clip()
.strokeStyle("#ffffff")
.lineCap("butt")
.lineJoin("miter")
.miterLimit(4)
.save().restore().save().restore().save().save().fillStyle("#bcbcbc").....

Categories

Resources