I'm trying to draw a circle in a HTML5 canvas and move it around.
I wrote this Javascript code:
var a = 0;
function draw() {
var c = document.getElementById("game");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(45+a, 45, 40, 0, 2 * Math.PI);
ctx.stroke();
a++;
}
var t=setInterval(draw,1000);
<canvas id="game" width="640" height="480"></canvas>
When I try to execute it, I get this error in the console:
TypeError: canvas.clearRect is not a function
How can I fix it?
Thank you.
In clearRect method, canvas.width and canvas.height will throw an error as canvas is undefined. You should be passing valid object.
var a = 0;
function draw() {
var canvas = document.getElementById("game");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(45 + a, 45, 40, 0, 2 * Math.PI);
ctx.stroke();
a++;
}
var t = setInterval(draw, 1000);
<canvas id="game" width="640" height="480"></canvas>
Related
I'm creating a pixel art app and when I want to save the image from the canvas the image is so small, so it seems pixelated when I want to resize it.
I want to resize it to bigger dimensions, but I don't know how.
This is the code example:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.rect(0, 0, 50, 50);
ctx.fillStyle = 'red';
ctx.fill();
document.write('<img style="width:300px;" src="'+c.toDataURL("image/png")+'"/>');
// This is an image with dimensions 108x108px and it seems very bad when i resize it to 300x300px
// I want to download the canvas image with more resolution
<canvas id="myCanvas" width="108" height="108" style="width: 300px; height:300px;">
</canvas>
you can create a canvas and put the imageData in it.
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.rect(0, 0, 25, 25);
ctx.fillStyle = 'red';
ctx.fill();
ctx.beginPath();
ctx.rect(0, 25, 25, 25);
ctx.fillStyle = 'yellow';
ctx.fill();
ctx.beginPath();
ctx.rect(25, 0, 25, 25);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.beginPath();
ctx.rect(25, 25, 25, 25);
ctx.fillStyle = 'green';
ctx.fill();
var c2 = document.createElement("canvas");
c2.width = 50;
c2.height = 50;
var ctx2 = c2.getContext("2d");
var imageData = ctx.getImageData(0, 0, 50, 50);
ctx2.putImageData(imageData, 0, 0);
document.write('<img style="width:300px;" src="' + c2.toDataURL("image/png") + '"/>');
hello i am trying to make a white circle move across a black box in javascript my circle is not showing up the big black box does but the circle does not show up i dont know why i am loading the page in google chrome here is the code
<html>
<head>
<title>paddle</title>
</head>
<body>
<canvas id="myCanvas" width="800" height="600"></canvas>
<script>
var canvas
var canvasContext
var ballX = 5
window.onload = function() {
var fps = 30;
setInterval(updateAll, 1000)
canvas = document.getElementById("myCanvas");
canvasContext = canvas.getContext("2d")
canvasContext.fillStyle = "black"
canvasContext.fillRect(0, 0, canvas.width, canvas.height)
}
function updateAll() {
ballX++
canvasContext.fillStyle = "white";
canvasContext.beginPath()
canvasContext.arc(ballX, 100, 10, 0, Math.PI*2, true);
canvasContext.stroke()
}
</script>
</body>
</html>
The problem is that you are using stroke to draw the circle but you have not set the stroke style which is by default black. So you are drawing a black circle on a black background. Hence no see circle.
Also it is best to use requestAnimationFrame to animate rather than set interval.
Example animating a circle
requestAnimationFrame(animationLoop);
const ctx = myCanvas.getContext("2d");
var ballX = 5;
var speed = 1
const radius = 10;
const fps = 30;
var frameCount = 0;
function animationLoop() {
if (frameCount % (60 / fps) === 0) {
ctx.fillStyle = "black"
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
draw();
}
frameCount ++;
requestAnimationFrame(animationLoop);
}
function draw() {
ballX = (ballX + speed) % (ctx.canvas.width + radius * 2);
ctx.strokeStyle = "white";
ctx.lineWidth = 2;
ctx.beginPath()
ctx.arc(ballX - radius, 20, 10, 0, Math.PI * 2);
ctx.stroke()
}
<canvas id="myCanvas" width="600" height="40"></canvas>
I've a <canvas> with an image already loaded and all the graphics coordinates needed for a crop (x, y, w, h) in an array.
What I'm trying to do is to crop the canvas directly, without a temporary other canvas to copy to/from (as suggested in other SO answers).
My idea is to:
1) Draw the selected area on the top-left corner of the canvas
2) Shrink the canvas size to the area
$('#edit').on("click", function() {
var img = $('#canvas');
var c = img[0];
var ctx = c.getContext("2d");
//var imageData = ctx.getImageData(0, 0, 100, 100);
ctx.drawImage(c, 0, 0, 100, 100, 0, 0, 100, 100);
c.width = 100;
c.height = 100;
});
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(0, 0, 350, 350);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="350" height="350"></canvas>
<input id="edit" type="button" value="Edit" />
Seems easy to me, but I'm missing something: when I execute, I get nothing https://jsfiddle.net/qg0znpu7/
What's wrong with my code? how can I fix it to obtain an in-place canvas crop?
Changing the width or height of a canvas will clear it. For that reason you will have to copy the data first.
You can use putImageData() for that:
$('#edit').on("click", function() {
var c = $('#canvas')[0];
var ctx = c.getContext("2d");
var imageData = ctx.getImageData(0, 0, 100, 100);
c.width = 100;
c.height = 100;
ctx.putImageData(imageData, 0, 0);
});
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(0, 0, 350, 350);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="350" height="350"></canvas>
<input id="edit" type="button" value="Edit" />
I need help trying to rotate the rectangle that I have drawn on the canvas. I would like the top of the rectangle to pivot either to the right or left once I press on the arrow keys on my keyboard. This is my code so far:
HTML:
<body >
<div id="canvas-container">
<canvas id="canvas" width="500" height="400"></canvas>
</div>
</body>
CSS:
canvas {
display: inline;
}
Javascript:
document.addEventListener("DOMContentLoaded", function() {
drawBorder();
});
var canvas;
var context;
var size;
drawRectangle();
drawHalfCircle();
function drawBorder() {
canvas = document.getElementById("canvas");
context = canvas.getContext('2d');
size = {
x: canvas.width,
y: canvas.height
};
//have to set colors etc befor it is drawn
context.strokeStyle = 'black';
//takes 4 parameters
context.strokeRect(0, 0, size.x, size.y);
}
function drawRectangle() {
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.rect(246, 290, 8, 80);
ctx.stroke();
}
function drawHalfCircle(){
var c= document.getElementById("canvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.arc(250,579,308,1.2*Math.PI, 1.8*Math.PI);
ctx.stroke();
}
I have mocked something up is this along the correct lines of what you are wanting.
document.addEventListener("DOMContentLoaded", function() {
drawBorder();
});
var canvas = document.getElementById("canvas");
var context = canvas.getContext('2d');
var size;
var angle = 0;
setInterval(function () {
context.save();
context.clearRect(0, 0, canvas.width, canvas.height);
drawBorder();
drawHalfCircle();
drawRectangle();
context.restore();
}, 100);
function drawBorder() {
size = {
x: canvas.width,
y: canvas.height
};
//have to set colors etc befor it is drawn
context.strokeStyle = 'black';
//takes 4 parameters
context.strokeRect(0, 0, size.x, size.y);
}
function drawRectangle() {
context.rotate(Math.PI / 180 * (angle));
context.rect(246, 290, 8, 80);
context.stroke();
}
function drawHalfCircle(){
context.beginPath();
context.arc(250,579,308,1.2*Math.PI, 1.8*Math.PI);
context.stroke();
}
document.onkeydown = function(e) {
var event = window.event ? window.event : e;
if (e.keyCode == '37') {
angle += 5;
}
else if (e.keyCode == '39') {
angle -= 5;
}
}
Basically set an interval and redraw (ie frames like in a movie) and rotate via a variable.
See a demo here
https://jsbin.com/qititacazu/edit?js,output
If you want to translate it so it will rotate around a different point do something like this.
context.translate(246, 290);
context.rotate(Math.PI / 180 * (angle));
context.rect(-4, 0, 4, 80);
The problem is demonstrated in the image below
In other words, how to exactly compute the x and y coordinates for every frame?
ctx.arc(x,y,radius,0,pi*2,false)
because after incrementing one coordinate, I have a problem how to compute the other
I tried this but doesn't work
var step=2,x=100,y=100,r=50,coordinates=[[x,y-r]];
for(var i=1;i <r;i+=step){
bx=x;
x+=step;
y=y-Math.sqrt(Math.pow(r,2)-Math.pow(bx-x,2))
coordinates[i]=[x,y];
}
a jsfiddle will be appreciated.
var canvas = document.querySelector("#c");
var ctx = canvas.getContext("2d");
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var speed = 10; // Lower is faster
function animate(t){
ctx.save();
ctx.clearRect (0 , 0 ,canvas.width ,canvas.height );
ctx.translate(canvas.width/2, canvas.height/2);
// First circle
ctx.beginPath();
ctx.arc(0, 0, 5, 0, 2 * Math.PI, false);
ctx.fillStyle = 'blue';
ctx.fill();
ctx.closePath();
// rotate + move along
ctx.rotate((t/speed)/100);
ctx.translate(100,0);
// Orbiting cirle
ctx.beginPath();
ctx.arc(0, 0, 10, 0, 2 * Math.PI, false);
ctx.fillStyle = 'red';
ctx.fill();
ctx.closePath();
ctx.restore();
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
canvas {
border: 1px solid black;
}
<canvas id="c" width="512" height="512"></canvas>