I'm trying to make a counter so that every time you click your mouse it shows the number of clicks in the canvas. But it isn't updating the canvas.
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<button onclick="function1()">Click Here</button>
<script>
var animate = setInterval(window.requestAnimationFrame,1)
var clicks = 0;
function function1()
{
clicks++;
document.getElementById('myCanvas').innerHTML = clicks;
};
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="16px Verdana";
ctx.fillText("Score: " + clicks,190,20);
</script>
</body>
</html>
So I changed the code to add a redraw() function to redraw on the canvas the new number.
And the increment() function will call that one after doing clicks++.
var clicks = 0;
function increment(){
clicks++;
redraw();
};
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
console.log(ctx);
function redraw(){
ctx.clearRect(0, 0, c.width, c.height);
ctx.font="16px Verdana";
ctx.fillText("Score: " + clicks,190,20);
}
redraw();
You can't just use innerHTML for canvas because it is really just a surface for drawing on thus it is not affected by it's inner DOM.
Here is a working JSFiddle demo.
Your code throws an error, window.requestAnimaitonFrame requires a callback to a function as parameter. This code works:
var animate = setInterval(function(){update()},1)
var clicks = 0;
function function1()
{
clicks++;
};
function update(){
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.clearRect(0,0,c.width,c.height);
ctx.font="16px Verdana";
ctx.fillText("Score: " + clicks,190,20);
}
Related
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/
I am creating an app which allows user to draw a digit(using mouse) in Canvas. When they click on submit, the image should be saved as a JPEG and Clear should Erase the digit drawn in canvas. I am new to HTML5 Canvas. I saw some tutorials which created a canvas, but I am unable to save and clear canvas. Any help would really be appreciated. Thanks.
Here is my HTML:
<div style="padding-bottom: 20px;padding-left: 210px;">
<div class="btn-group" role="group" aria-label="...">
<button type="button" id="save" class="btn btn-default">Submit</button>
<button type="button" id="clear" class="btn btn-default">Clear</button>
</div></div>
</div>
Javascript within Script tag:
var clear = document.getElementById('clear');
clear.addEventListener('click', clearCanvas);
var clearCanvas = function(e) {
ctx.fillStyle = "white";
ctx.fillRect(0, 0, 500, 400);
ctx.clearRect(20, 20, 100, 50);
}
The tutorial you're using fails to mention a few key things:
The canvasInAPerfectWorldline isn't used: you can delete it.
You need jQuery: just add <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script/> in your <head> section.
You should wrap your javascript in the jQuery boilerplate, to ensure it gets executed after the rest to the document has loaded: $( document ).ready(function() { <your javascript here> });
The canvasWidth and canvasHeight variables are never set: add this line before the variables are used:var canvasWidth = 600; var cavasHeight = 400;
The variables mouseX and mouseY are never used: you can delete them (but take a look at the onClick() function two lines later to see what they would have been used for).
The finished result should look like this:
<!DOCTYPE html>
<html>
<head>
<title>HTML5 Create HTML5 Canvas JavaScript Drawing App Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<style>canvas { border: 1px solid #ccc; }</style>
<script type="text/javascript">
$( document ).ready(function() {
var canvasWidth = 600; var cavasHeight = 400;
var canvasDiv = document.getElementById('canvasDiv');
canvas = document.createElement('canvas');
canvas.setAttribute('width', canvasWidth);
canvas.setAttribute('height', cavasHeight);
canvas.setAttribute('id', 'canvas');
canvasDiv.appendChild(canvas);
if(typeof G_vmlCanvasManager != 'undefined') {
canvas = G_vmlCanvasManager.initElement(canvas);
}
context = canvas.getContext("2d");
$('#canvas').mousedown(function(e){
paint = true;
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop);
redraw();
});
$('#canvas').mousemove(function(e){
if(paint){
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
redraw();
}
});
$('#canvas').mouseup(function(e){
paint = false;
});
$('#canvas').mouseleave(function(e){
paint = false;
});
$('#clear').click(function(){
clickX.length = 0;
clickY.length = 0;
clickDrag.length = 0;
redraw();
});
var clickX = new Array();
var clickY = new Array();
var clickDrag = new Array();
var paint;
function addClick(x, y, dragging)
{
clickX.push(x);
clickY.push(y);
clickDrag.push(dragging);
}
function redraw(){
context.clearRect(0, 0, context.canvas.width, context.canvas.height); // Clears the canvas
context.strokeStyle = "#df4b26";
context.lineJoin = "round";
context.lineWidth = 5;
for(var i=0; i < clickX.length; i++) {
context.beginPath();
if(clickDrag[i] && i){
context.moveTo(clickX[i-1], clickY[i-1]);
}else{
context.moveTo(clickX[i]-1, clickY[i]);
}
context.lineTo(clickX[i], clickY[i]);
context.closePath();
context.stroke();
}
}
});
</script>
</head>
<body>
<div id="canvasDiv"></div>
</body>
</html>
As for saving your canvas as a JPEG, that's more complicated. As markE has pointed out, there's a related question here which shows one way to do it.
EDIT: Adding a 'Clear' button:
Your 'drawing' is really just a series of pen movements stored in the clickX, clickY and clickDrag arrays. Each time redraw() is called, the drawing gets recreated from the arrays. So just drawing a white rectangle will only clear the screen until the next redraw(). Instead, you can clear the arrays by adding this to your javascript:
$('#clear').click(function(){
clickX.length = 0;
clickY.length = 0;
clickDrag.length = 0;
redraw();
});
(BTW by deleting the details of your original question, you make it hard for the next person to understand the context of the answers. You should either (a) add to your original question, or (b) ask a new question. Also you can upvote and/or accept any answers you find helpful. Thanks)
I think that's a duplicated question. See here
Can I get image from canvas element and use it in img src tag?
var image = new Image();
image.id = "pic"
image.src = canvas.toDataURL();
document.getElementById('image_for_crop').appendChild(image);
Im pretty new to the canvas element in HTML5.
What i want to do is move an image from the right hand side of the screen to the left, once it reaches the left i want it to begin again from the right hand side. I only want it to do this maybe 2/3 times and then stop.
I tried to add in a for loop so that it would limit the iterations but this was unsuccessful.
Any help at all would be appreciated.
Heres my code:
<canvas id="myCanvas" width="600" height="400"></canvas>
<script>
window.addEventListener('load', function () {
var
img = new Image,
ctx = document.getElementById('myCanvas').getContext('2d');
img.src = 'pies.png';
img.addEventListener('load', function () {
var interval = setInterval(function() {
var x = 650, y = 194;
return function () {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.drawImage(img, x, y);
x -= 1;
if (x < -500) {
x = 650;
}
};
}(), 1000/40);
}, false);
}, false);
</script>
One way is to specify a maximum number of leftward moves:
// allow leftward moves = 2 1/2 time the canvas width
// (plus an allowance for the image width)
var maxMoves = (canvas.width+image.width) *2.5;
Then just countdown maxMoves until zero. At zero, stop your animation:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
ctx.fillStyle='skyblue';
var currentX=cw;
var delay=16; // 16ms between moves
var continueAnimating=true;
var nextMoveTime,maxMoves;
var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/sun.png";
function start(){
maxMoves=(cw+img.width)*2.5;
nextMoveTime=performance.now();
requestAnimationFrame(animate);
}
function animate(currentTime){
if(continueAnimating){ requestAnimationFrame(animate); }
if(currentTime<nextMoveTime){return;}
nextMoveTime=currentTime+delay;
ctx.fillRect(0,0,cw,ch);
ctx.drawImage(img,currentX,50);
if(--currentX<-img.width){ currentX=cw; }
if(--maxMoves<0){continueAnimating=false;}
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<p>Stop animating after 2 1/2 "sunrises"</p>
<canvas id="canvas" width=300 height=300></canvas>
In the following code i want to rotate the text of each element of the array in javascript. If i use for example ctx.rotate(Math.PI/10) before the filltext, it rotates all the elements. The positioning of the text also changes with ctx.rotate(Math.PI/10) and if i use 90 degrees, ctx.rotate(Math.PI/2) the text does not show on the canvas.
<html>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid #d3d3d3;"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var x = new Array("Day1","Day2","Day3","Day4","Day5");
ctx.rotate(Math.PI/10);
for(var i = 0; i < x.length; i++){
ctx.fillText(x[i],i*50+20,50);
}
</script>
</html>
As i said, i want to rotate each element on its own and with that the positioning of each element should stay the same as in the non-rotated text as in the code above. Thus each element has to rotate around its own axis. How can i achieve this?
Have made some changes in your code, it should help:
<html>
<canvas id="myCanvas" width="300" height="300" style="border:1px solid
#d3d3d3;"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var x = new Array("Day1","Day2","Day3","Day4","Day5");
for(var i = 0; i < x.length; i++){
var size = ctx.measureText(x[i]);
ctx.save();
var tx = (i*50+20) + (size.width/2);
var ty = (50);
ctx.translate(tx,ty);
ctx.rotate(Math.PI / 10);
ctx.translate(-tx,-ty);
ctx.fillText(x[i],i*50+20,50);
ctx.restore();
}
</script>
</html>
Demo: http://jsfiddle.net/m1erickson/YyN2P/
A brief overview:
context.translate to where you want the rotation point of the text
context.rotate
context.fillText with an X offset == 1/2 the text width and Y offset == 1/2 the text height
(you can context.measureText to measure the text width)
wrap all this in context.save and context.restore.
use requestAnimationFrame to drive your animation.
And some example code:
var word1="Day1";
var word1Width=ctx.measureText(word1).width;
var r=0;
animate();
function animate(){
requestAnimationFrame(animate);
r+=Math.PI/180;
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(100,100);
ctx.rotate(r);
ctx.fillText(word1,-word1Width/2,4);
ctx.restore();
}
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);