HTML5 - Draw on canvas after timeout - javascript

I am trying to draw a line on a canvas after a timeout period. One of the "lineTo" parameters is being sent a value from a variable that is being declared in another script and is being passed as a window.var....
I have a console log set up to execute at the same time as the variable is accessed in the canvas script as well.
onLoad, everything executes as it should. After the timeout, the console shows that the variable has a value, but the canvas line is not drawn.
At first I had no timeout inserted and the variable kept coming back as undefined. I opted to go with a timeout, as I don't fully understand callbacks yet.
Any advice would be greatly appreciated!
<script>
window.setTimeout(render,8500);
function render(){
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var end = window.testVar;
context.beginPath();
context.moveTo(4, 28);
context.lineTo(end, 28);
context.lineWidth = 10;
context.stroke();
console.log(end);
}
</script>

context.lineTo expects a number, so cast your testVar to a number
For example:
var end = parseInt(window.testVar);
Your code above works fine for me...the line draws itself after the specified delay:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
window.testVar=23;
window.setTimeout(render,2000);
function render(){
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var end = window.testVar;
context.beginPath();
context.moveTo(4, 28);
context.lineTo(end, 28);
context.lineWidth = 10;
context.stroke();
console.log(end);
}
body{ background-color: ivory; }
canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>

User error....
I'm using WYSIWYG Web Builder, and I'm using layers. Some how, the canvas element was marked as "visibility: hidden";
Since the background of the canvas is transparent, I didn't catch it.
To all, thanks for commenting.

Related

Trouble Drawing Circle in JS and moving them

today i've got a problem regarding JavaScript.
I was given an exercise which consists on create a circle on the screen, using JavaScript, and then make it move to the right.
So the problem comes when i put in the function animate().
The code by itself works, it creates a circle, but when i insert the function animate() , put the code in it, and then try to recall it with requestFrameAnimation(animate), it just doesn't draw on the screen.
Code right down here. I've tried everything i am capable of, but couldn't fix it.
Thanks for the replies.
HTML:
<head>
<style type="text/css">
canvas{
border:1px solid black;
}
body{
margin:0px;
background-color:red;
</style>
</head>
<body>
<canvas></canvas>
<script src="canvas.js"></script>
</script>
</body>
JS:
canvas = document.querySelector('canvas'); //CANVAS SELECTOR
canvas.width = window.innerWidth; //MATCHING THE CANVAS WIDTH WITH THE WINDOW WIDTH
canvas.height = window.innerHeight; //********************HEIGHT***************HEIGHT
context=canvas.getContext("2d");
var x=200;
function animate(){ //Starting the function
context.beginPath(); //Initializing a Path of drawings
context.arc(x,200,100,0,Math.PI*2, true); //drawing the circle
context.fillStyle="rgba(120,10,200,0.5)"; //filling the circle
context.fill();
context.strokeStyle = 'blue'; //giving the circle a strokeline
context.stroke();
x+=1; //increasing the circle x so that it keeps moving towards right
requestAnimationFrame(animate); //calling back to the function so it keeps drawing infinitely.
}

setTimeout() not working in animation function | Animation not working

I'm trying to build a very simple animation function. I'm using this tutorial to build my project:
https://www.youtube.com/watch?v=hUCT4b4wa-8
The result after the button is clicked should be a green box moving across the page from left to right. When the button is clicked, nothing happens and I don't get any console errors.
Here's my fiddle:
https://jsfiddle.net/xkhpmrtu/7/
And here's a snippet of my code:
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<style type="text/css">
canvas {
border: 1px solid #666;
}
</style>
<script type="application/javascript" language="javascript">
function anim(x,y) {
var canvas = document.getElementById('canvas');//reference to canvas element on page
var ctx = canvas.getContext('2d');//establish a 2d context for the canvas element
ctx.save();//save canvas state if required (not required for the tutoriral anaimation, but doesn't hurt the script so it stays for now)
ctx.clearRect(0, 0, 550, 400);//clears the canvas for redrawing the scene.
ctx.fillStyle = "rgba(0,200,0,1)";//coloring the rectangle
ctx.fillRect = (x, 20, 50, 50);//drawing the rectangle
ctx.restore();//this restores the canvas to it's original state when we saved it on (at the time) line 18
x += 5; //increment the x position by some numeric value
var loopTimer = setTimeout('draw('+x+','+y+')', 2000);// setTimeout is a function that
</script>
</head>
<body>
<button onclick="animate(0,0)">Draw</button>
<canvas id="canvas" width="550" height="400"></canvas>
</body>
Any idea what I'm doing wrong?
I just had a look at the tutorial link. I will give if a major thumbs down as it demonstrates how not to animate and how not to do many other things in Javascript.
First the script tag and what is wrong with it
// type and language default to the correct setting for javascrip
// <script type="application/javascript" language="javascript">
<script>
function anim(x,y) {
// get the canvas once. Getting the canvas for each frame of an
// animation will slow everything down. Same for ctx though will not
// create as much of a slowdown it is not needed for each frame
// var canvas = document.getElementById('canvas');
// var ctx = canvas.getContext('2d');
// Dont use save unless you have to. It is not ok to add it if not needed
// ctx.save();
// dont use literal values, canvas may change size
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "rgba(0,200,0,1)";
// this line is wrong should be ctx.fillRect(x, 20, 50, 50). It is correct in the video
ctx.fillRect = (x, 20, 50, 50);//drawing the rectangle
// restore not needed
//ctx.restore();
x += 5; //increment the x position by some numeric value
// creating a string for a timer is bad. It invokes the parser and is slooowwwwww...
// For animations you should avoid setTimeout altogether and use
// requestAnimationFrame
// var loopTimer = setTimeout('draw('+x+','+y+')', 2000);
requestAnimationFrame(draw);
// you were missing the closing curly.
}
</script>
There is lots more wrong with the tut. It can be excused due to it being near 5 years old. You should look for more up todate tutorials as 5 years is forever in computer technology.
Here is how to do it correctly.
// This script should be at the bottom of the page just befor the closing body tag
// If not you need to use the onload event to start the script.
// define a function that starts the animation
function startAnimation() {
animating = true; // flag we are now animating
x = 10;
y = 10;
// animation will start at next frame or restart at next frame if already running
}
// define the animation function
function anim() {
if (animating) { // only draw if animating
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "red"; //coloring the rectangle
ctx.fillRect(x, y, 50, 50); //drawing the rectangle
x += xSpeed;
}
// set animation timer for next frame
requestAnimationFrame(anim);
}
// add a click listener to the start button. It calls the supplied function every time you click the button
startAnimButton.addEventListener("click", startAnimation);
const ctx = canvas.getContext('2d'); // get the 2d rendering context
// set up global variables to do the animation
var x, y, animating;
animating = false; // flag we are not animating
const xSpeed = 50 / 60; // Speed is 50 pixels per second at 60fps
// dont slow the animation down via frame rate
// slow it down by reducing speed.
// You only slow frame rate if the machine
// can not handle the load.
// start the animation loop
requestAnimationFrame(anim);
canvas {
border: 1px solid #666;
}
<!-- don't add events inline -->
<button id="startAnimButton">Draw</button>
<canvas id="canvas" width="512" height="128"></canvas>

Javascript - Putting ImageData Onto a Canvas Element - CanvasRenderingContext2D

I want to take a source image and put its pixel data into a element with a CanvasRenderingContext2D grid.
I'm writing a javascript function to work with certain pixel points of data,
but I keep getting an error from this line:
ctx.putImageData(sourceImage, 0, 0);
Here is my current javascript function that accepts a class ID of an img element as its argument:
function mapMyImage(sourceImageID) {
// Declare variable for my source image
var sourceImage = document.getElementById(sourceImageID);
// Creates a canvas element in the HTML to hold the pixels
var canvas = document.createElement('canvas');
// Create a 2D rendering context for our canvas
var ctx = canvas.getContext('2d');
// After the image has loaded, put the source image data into the
// 2D rendering context grid
function imgToPixelArray() {
// In the context of the canvas, make an array of pixels
ctx.putImageData(sourceImage, 0, 0);
}
// Call the above function once the source image has loaded
sourceImage.onload = imgToPixelArray();
// Get Access to the pixel map now stored in our 2D render
var imageData = ctx.getImageData(0, 0, 400, 300);
}
Why am I getting an error when I am trying to put my source image's pixel data into a 2D rendering context grid?
It looks like you want to clip a 400x300 subsection of the image and draw it into the canvas.
You don't need .getImageData and .putImageData to accomplish that.
You can use the clipping version of .drawImage to do that:
context.drawImage(
img, // the image source
0,0, // start clipping from the source at x=0, y=0
400,300 // clip a subsection that's 400x300 in size
0,0 // draw that clipped subsection on the canvas at x=0,y=0
400,300 // make the drawing 400x300 (don't scale)
)
Here's example code and a Demo:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/landscape2.jpg";
function start(){
ctx.drawImage(img, 0,0,400,300, 0,0,400,300);
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<h4>subsection clipped to the canvas</h4>
<canvas id="canvas" width=400 height=300></canvas>
<h4>The original image</h4>
<img src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/landscape2.jpg">

How to fix text overlapping with setInterval and fillStyle?

I am very new to JavaScript and have very little knowledge about why certain symbols/characters act the why they do. So if you don't mind explaining a bit how the fix helped my code that would be a huge boost in my understanding. Thanks!
<canvas id="myCanvas" width="600" height="400"></canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var interval = setInterval(function()
{
var time= new Date()
ctx.font="30px Verdana";
// Create gradient
var gradient=ctx.createLinearGradient(0,0,c.width,0);
gradient.addColorStop("0","green");
gradient.addColorStop("0.5","blue");
gradient.addColorStop("1.0","green");
// Fill with gradient
ctx.fillStyle=gradient;
ctx.fillText(time,10,90);
},10)
</script>
You need to clear the canvas prior to drawing the text. Add the following code to the beginning of your setInterval function:
ctx.clearRect(0, 0, c.width, c.height);

Cannot call draw function in javascript

I have a project creating layouts and i have decided to do it with canvas element.I created a function that takes 4 args.
function fillArc(camvas,x,y,w,h)
{
canv.beginPath();
var canv = document.getElementById("camvas");
var context = canv.getContext('2d');
context.strokeStyle="#FFFFFF";
context.moveTo(x+5,y);
context.lineTo(w-5,y);
context.quadraticCurveTo(w,y,w,y+5);
context.lineTo(w,h-5);
context.quadraticCurveTo(w,h,w-5,h);
context.lineTo(x+5,h);
context.quadraticCurveTo(x,h,x,h-5);
context.lineTo(x,y+5);
context.quadraticCurveTo(x,y,x+5,y);
context.stroke();
canv.closePath();
}
I have several canvas elements so i want to create this border-radius box in different areas.I assumed that a call like:
<canvas width="500" height="500" id="canvaslayouts">
</canvas>
<script>
fillArc(canvaslayouts,10,10,50,50);
</script>
But this doesn't seem to work.Can anyone point my mistake please.
jsFiddle Demo
Place your function and the call to it in a script element
Pass in a string which matches the id of the canvas you wish to draw on
Use the context, not the canvas, to access the drawing API
<script>
function fillArc(camvas,x,y,w,h)
{
var canv = document.getElementById(camvas);
var context = canv.getContext('2d');
context.beginPath();
context.strokeStyle="#ffffff";
context.moveTo(x+5,y);
context.lineTo(w-5,y);
context.quadraticCurveTo(w,y,w,y+5);
context.lineTo(w,h-5);
context.quadraticCurveTo(w,h,w-5,h);
context.lineTo(x+5,h);
context.quadraticCurveTo(x,h,x,h-5);
context.lineTo(x,y+5);
context.quadraticCurveTo(x,y,x+5,y);
context.stroke();
context.closePath();
}
fillArc("canvaslayouts",10,10,50,50);
</script>
Putting it in a <script> block should do the trick:
<canvas width="500" height="500" id="canvaslayouts"></canvas>
<script>
fillArc(canvaslayouts,10,10,50,50);
</script>
Also, note that your fillArc() function definition (or any other executable JavaScript that you may have) should also be in a <script> block.
Well, a few things:
You're never using the camvas variable.
You're always refering to #camvas.
You call canv.beginPath() before setting canv to anything.
Your javascript code in the canvas is not in script tags
Your javascript code in the canvas tag calls the function with canvaslayouts as the first parameter. This means you're searching for a variable named "canvaslayouts" and not an ID. Change it to "canvaslayouts" to specify that it's a string to be used in getElementById.
The correct code should be something like this:
function fillArc(camvas,x,y,w,h)
{
//Changed to use the variable instead, and moved it to the start
var canv = document.getElementById(camvas);
canv.beginPath();
var context = canv.getContext('2d');
context.strokeStyle="#FFFFFF";
context.moveTo(x+5,y);
context.lineTo(w-5,y);
context.quadraticCurveTo(w,y,w,y+5);
context.lineTo(w,h-5);
context.quadraticCurveTo(w,h,w-5,h);
context.lineTo(x+5,h);
context.quadraticCurveTo(x,h,x,h-5);
context.lineTo(x,y+5);
context.quadraticCurveTo(x,y,x+5,y);
context.stroke();
canv.closePath();
}
and
<canvas width="500" height="500" id="canvaslayouts">
<script type="text/javascript">
//Use a script container
fillArc("canvaslayouts",10,10,50,50); //Use a string, not a variable
</script>
</canvas>
You need to change the .beginPath() and .closePath() calls so that they're applied to the context, and not to the canvas.
That can of course only be done once you've called canv.getContext().
You also need to:
use the correct ID - you've used "camvas" when it should be the variable with that name
put your JS inside <script> tags
i.e.:
<script>
function fillArc(camvas,x,y,w,h)
{
var canv = document.getElementById(camvas);
var context = canv.getContext('2d');
context.beginPath();
context.strokeStyle="#FFFFFF";
context.moveTo(x+5,y);
context.lineTo(w-5,y);
context.quadraticCurveTo(w,y,w,y+5);
context.lineTo(w,h-5);
context.quadraticCurveTo(w,h,w-5,h);
context.lineTo(x+5,h);
context.quadraticCurveTo(x,h,x,h-5);
context.lineTo(x,y+5);
context.quadraticCurveTo(x,y,x+5,y);
context.closePath(); // NB: close the path before you stroke it
context.stroke();
}
</script>
<canvas width="500" height="500" id="canvaslayouts"> </canvas>
<script>
fillArc("canvaslayouts", 10, 10, 50, 50);
</script>

Categories

Resources