I am unable to draw rectangles in canvas within for loop in JavaScript. Sometimes they are visible for a fraction of second, but they disappear instantly. No errors in developer console - tested on Firefox & Chrome, so problem isn't browser-related. Seems like only I encountered this issue within my class, despite having exactly the same (or slightly adjusted to my needs) code.
Code was tested on multiple browsers, the problem itself seems to occur only on my laptop/browser - rest of my colleagues haven't encountered this issue, apart from some typos etc.
The general idea is to receive a result similar to this one:
function Draw() {
var l = liczba.value; // user-input based loop control
var xpos = ypos = 300; // Left side rectangles starting drawing position
var xneg = 600, yneg = 300; // Right side rectangles starting drawing position
var canvas = document.getElementById('image');
var context = canvas.getContext('2d');
context.fillStyle = 'red';
for(var i = 0; i < l; i++) {
context.fillRect(xpos, ypos, 100, 100);
context.strokeRect(xpos, ypos, 100, 100);
console.log("Left Canvas Painted!"); // Debug
context.fillRect(xneg, yneg, 100, 100);
context.strokeRect(xneg, yneg, 100, 100);
console.log("Right Canvas Painted!"); // Debug
xpos += 50; xneg -= 50; ypos += 50; yneg += 50; // change next canvas' starting position by...
}
}
<body>
<form method="post" id="f" onsubmit="Draw();">
<label>Podaj liczbę figur do narysowania: </label>
<input type="text" name="liczba" id="liczba">
<input type="submit" name="send" id="send" value="Zatwierdź">
</form>
<canvas id="image" width="1200" height="800">Canvasy nie działają</canvas>
</body>
Try changing the button from a submit button to a normal button and call Draw() on a click event.
<input type="button" onclick="Draw()" name="send" id="send" value="Zatwierdź">
The answer to this issue was pretty straight-forward, thanks to #jcbbdrn - a minor oversight on my part. Due to page reload on form submitting, whole canvas was flushed down the toilet. After implementing a regular button and assigning to it an onclick event, the problem has been solved.
Related
For an assignment I need to animate something simple using CSS and JavaScript. I've been able to figure out the CSS but everything I read to make an object fade in using JavaScript just doesn't seem to work with the object I drew in JavaScript. I just wanted to draw a circle in JavaScript and then animate it to fade in in 5 seconds.
Here is the basic Code I have so far:
HTML:
<body onload="draw();">
<canvas id="circle" width="450" height="450"></canvas>
</body>
JavaScript:
<script>
function draw()
{
var canvas = document.getElementById('circle');
if (canvas.getContext)
{
var ctx = canvas.getContext('2d');
var X = canvas.width / 2;
var Y = canvas.height / 2;
var R = 45;
ctx.beginPath();
ctx.arc(X, Y, R, 0, 2 * Math.PI, false);
ctx.lineWidth = 3;
ctx.strokeStyle = '#645862';
ctx.stroke();
}
}
</script>
As you can see I only have the circle part of the code. I have tried multiple versions of different fade in animations but I just can't quite get them to work. I'm not very good at JavaScript. It's the one language I have trouble understanding for some reason. I'm also really sick right now otherwise I would be troubleshooting more reasons as to why it isn't working.
To understand how a canvas works, you need to know that it's just a place to display something, and initially it doesn't do anything on its own. You've drawn the circle once, which is enough to display the circle, but not to animate it in any way.
If we want to move the circle in any direction, we must clear the canvas of the already drawn circle and draw the circle in a different place, changing its coordinates by N pixels. The same goes for transparency. We must change the transparency of the color of the circle in each frame, and draw the circle again and again.
This is how 2D and 3D canvas works, as well as all video games - they draw scenes 60 times per second, changing some values along the way, such as coordinates, values, color, transparency, height and width.
In order for this to work, we need two additional variables, opacity and the direction (fading) in which the opacity changes, to know whether the circle appears or disappears.
Also important is the recursive call to our draw() function. We will call it constantly, and we will constantly redraw our image on the canvas.
I also want to point out some conceptual mistakes in your code.
Dont use "var", it is deprecated. Use "let","const". Also don`t repeat "var","var","var" in every line. Use commas.
Dont use onload,onclick and others HTML on-attributes. They are only suitable for educational purposes, not for real work. Use script tag and document event listeners.
Dont name canvas id like "circle","box" etc. It is not a circle and a box, it is a canvas.
Use document.querySelector instead of document.getElementById. It is more modern
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas opacity animation</title>
</head>
<body>
<canvas id="canvas" width="450" height="450"></canvas>
<script>
document.addEventListener("DOMContentLoaded",()=>{
const OPACITY_SPEED = .005
let canvas = document.querySelector('canvas'),
context = canvas.getContext('2d'),
opacity = 1,
fading = true
draw()
function draw(){
// clear canvas for redrawing (important!)
context.clearRect(0, 0, canvas.width, canvas.height);
let circleX = canvas.width/2,
circleY = canvas.height/2,
radius = 45
// changing circle opacity
if(fading) opacity -= OPACITY_SPEED
else opacity += OPACITY_SPEED
// check if we need to fade in or to fade out
if(opacity >= 1) fading = true
if(opacity <= 0) fading = false
// draw circle
context.beginPath();
context.arc(circleX, circleY, radius, 0, 2 * Math.PI, false);
context.lineWidth = 3;
context.strokeStyle = `rgba(0, 0, 0, ${opacity})`;
context.stroke();
// call draw() again and again
requestAnimationFrame(draw)
}
})
</script>
</body>
</html>
I want to get the data from input tags and use them in the equation.
I have tried a lot a lot of solutions, nothing worked.
I want it to start setup after click one button, and start animate after pressing the other button.
press button1
load the data from the html
set up the canvas using those data
execute draw() for ever.
I did not find much documentation.
Here is my html:
<label class="col-lg-2" for="n4" id="m2">mass sq 2</label>
<input class=" col-lg-2" name="n4" type="number" id="m2" label="mass sq 2" />
<label class="col-lg-2" for="n5" id="r">Ratio</label>
<input class="ana col-lg-2" name="n5" type="number" id="r" label="Ratio" />
<button class="col-lg-2 btn btn-danger" style="margin-left: 10%;
height:30px;"> <h3> change </h3> </button>
and here is the p5.js code:
button1 = CreateButton('submit1');
button2 = CreateButton('submit2');
let digits = document.getElementById('m2').Value;
const timeSteps = 10 ** (digits - 1);
let m1 = document.getElementById('m1').Value;
function preload() {
blockImg = loadImage('block.png');
clack = loadSound('clack.wav');
}
function setup() {
button2.mousePressed(start);
}
function draw() {
button2.mousePressed(finish);
}
function start() {
createCanvas(windowWidth, 200);
block1 = new Block(100, 20, m1, 0, 0);
const m2 = pow(100, digits - 1);
block2 = new Block(300, 100, m2, -1 / timeSteps, 20);
countDiv = createDiv(count);
countDiv.style('font-size', '72pt');
}
This answer uses instance mode to create a canvas with width and height set from user inputs. This allows us to call createCanvas() inside of setup. The code only allows us to create one canvas but it would not be hard to modify so that multiply canvases could be created, however, we should never call createCanvas more than once for each instance of p5.
var canvas = null;
function createP5 (){
let canvasWidth = document.getElementById("widthInput").value;
let canvasHeight = document.getElementById("heightInput").value;
if (canvas === null){
canvas = new p5(function (p) {
p.setup = function (){
p.createCanvas(canvasWidth, canvasHeight);
}
p.draw = function(){
p.background(55);
p.stroke(0);
p.rect(p.width/5, p.height/5, p.width/5 * 3, p.height/5 * 3);
}
}, "canvas-div");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.min.js"></script>
<div id="canvas-div">
</div>
<input type="button" value="create canvas" onclick='createP5()'/>
<textarea id="widthInput"></textarea>
<textarea id="heightInput"></textarea>
You're asking a few different questions:
How do I run code when a user presses a button?
There are a few ways to do this, but it sounds like you're looking for the onclick attribute. You can Google "JavaScript onclick" for a ton of resources.
How do I run a P5.js sketch from JavaScript code?
For this, you probably want to use instance mode to have more control over exactly when the sketch is created. See this page for more info.
The best advice I can give you is to start smaller. Start with a simple page that shows a single button that prints something to the console when you click it. Then add a simple P5.js sketch using instance mode. Work forward in small steps instead of trying to do everything all at once.
Good luck.
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>
I have a problem with the click function in javascript. This is my code:
var canvas = document.getElementsByTagName("canvas")[0];
var ctx = canvas.getContext('2d');
BigCircle = function(x, y, color, circleSize) {
ctx.shadowBlur = 10;
ctx.shadowColor = color;
ctx.beginPath();
ctx.arc(x, y, circleSize, 0, Math.PI * 2, true);
ctx.fill();
ctx.closePath();
};
var bigGreen = new BigCircle(1580, 800, '#5eb62b', 180);
function init() {
$("#bigGreen").click(function(e){
alert("test");
});
}
$(document).ready(function() {
init();
});
But the click event is not working! Does anybody know why? Thank you so much in advance!
You can now use hit regions in Chrome and Firefox:
https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility#Hit_regions
(Edit: Hit regions are now obsolete)
or just use one of the many canvas APIs:
http://www.fabricjs.com/
http://www.createjs.com/easeljs
http://www.paperjs.org
etc...
without seeing your html this question is a little bit unclear, it seems you would like to draw something on a canvas and use jquery to add click events for the circle, this isn't possible.
you can use jquery to get the click event ON the canvas and from the cursor position you can calculate if the user clicked the circle or not, but jquery won't help you here you have to do the math yourself.
jquery does only work for dom elements.
BigCircle = function(ctx,x, y, color, circleSize) {
ctx.beginPath();
ctx.arc(x, y, circleSize, 0, Math.PI * 2, true);
ctx.fillStyle=color
ctx.fill();
ctx.closePath();
this.clicked=function(){
ctx.fillStyle='#ff0000'
ctx.fill();
}
};
function init() {
var canvas = document.getElementsByTagName("canvas")[0];
var ctx = canvas.getContext('2d');
var bigGreen = new BigCircle(ctx,50, 50, '#5eb62b', 50);
$('#canvas').click(function(e){
var x = e.clientX
, y = e.clientY
if(Math.pow(x-50,2)+Math.pow(y-50,2) < Math.pow(50,2))
bigGreen.clicked()
})
}
$(document).ready(function() {
init();
});
jsfiddle is here
http://jsfiddle.net/yXVrk/1/
Canvas API function isPointInPath() can be used to assist with hit detection. This function can at least tell if mouse coordinates are within a complex shape without doing sophisticated math yourself. May work for simple shapes as well but my use case was for on a bezier curve path. However, you need to either incorporate this function in your drawing logic to test while paths are open or keep an array of Path2d objects to test against. I redraw on onClick handler and pass in mouse coords from event args, but I think I could have kept an array of Path2d objects instead.
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/isPointInPath
bigGreen is not in the HTML, so $("#bigGreen") selects nothing. You can't put a click function on things like JavaScript functions; since they don't exist in the DOM, how could you click one? You should replace #bigGreen with #canvas, since "canvas" is your HTML element.
I forked your fiddle to show this here.
Edit: If you want to see that the user clicked on a particular circle, you use the canvas click event, and then, you determine which circle was clicked by the coordinates passed into the click event.
Edit: Demo Code is found in the "parallelogram explorer" tab here: http://atmdev01.procloud.net/geometry_tools9/
So I'm calling the following javascript function at document load to draw the perimeter of a parallelogram, and it is working just fine to do that. The issue is when I call the function from the touchmove handler to allow an iPad user to adjust the size of the parallelogram, the canvas is not properly redrawing the shape. In fact it is not responding at all. I've run some alerts to verify that this function is actually being run and it is.
Could it be an issue with the way I'm clearing the canvas (the "canvas.width = canvas.width + 0" method) or simply with refresh rates on the iPad?
The interesting part is that it's working perfectly in a desktop browser using mousemove, but not on an iPad using touchmove. Please advise...
(the "corners" in the code are the areas where the user can touch and drag to resize the parallelogram)
this.drawSides = function() {
var order = [1, 2, 4, 3];
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var firstCorner = this.getCornerObj(1);
var secondCorner = this.getCornerObj(2);
var firstCornerOpp = this.getCornerObj(firstCorner.opp);
var secondCornerOpp = this.getCornerObj(secondCorner.opp);
/* Clear the canvas and draw a parallelogram with the provided corners */
canvas.width = canvas.width + 0; //clears the canvas faster than clearRect
ctx.beginPath();
for (i in order) {
if (i < order.length) {
var cornerObj = this.getCornerObj(order[i]);
if (order[i] > 1) {
var prevObj = this.getCornerObj(order[i-1]);
ctx.moveTo(prevObj.x + (prevObj.width)/2, prevObj.y + (prevObj.height)/2);
ctx.lineTo(cornerObj.x + (cornerObj.width)/2, cornerObj.y + (cornerObj.height)/2);
}
}
}
ctx.lineTo(firstCorner.x + (firstCorner.width)/2, firstCorner.y + (firstCorner.height)/2);
ctx.strokeStyle = "#300";
ctx.stroke();
}
The canvas isn't cleared properly with canvas.width = canvas.width; in safari.
Keep in mind that it's less computationally expensive to clear the canvas using context.clearRect() than it is to reset the canvas size. This is really important for mobile devices and tablets.
Reference: http://www.html5rocks.com/en/tutorials/canvas/performance/#toc-clear-canvas
I've resolved this issue. Turns out the issue was that I wasn't properly updating my cornerObjects' x and y coordinates on touchmove. (the code excerpt above has no issue)
Also, for future reference, canvas.width = canvas.width + 0; works just fine on Safari and the iPad.