I want to clear a full canvas. But using clearRect() isn't doing anything. So how can I remove the drawn picture from my canvas?
<canvas id="myCanvas" width="600" height="580"></canvas>
<script>
window.onload = function() {
canv = document.getElementById("myCanvas");
ctx = canv.getContext("2d");
falcon = document.getElementById("milenium_falcon");
ctx.drawImage(falcon, 315, 500, 75, 75);
document.addEventListener("keydown",keyPush);
setInterval(game,1000/15);
}
x = 0;
function game() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(falcon, 315 - x, 500, 75, 75);
}
function keyPush(evt) {
switch(evt.keyCode) {
case 37:
x -= 5;
break;
case 39:
x += 5;
break;
}
}
</script>
In your call to .clearRect(), you are using the variable canvas instead of canv. It should work if you use this line instead:
ctx.clearRect(0, 0, canv.width, canv.height);
Related
This question already has answers here:
How to clear the canvas for redrawing
(25 answers)
Closed 3 years ago.
I want to make a rectangle that moves from the right to the left.
I could draw a new rectangle in the left of the previous one but i couldn't erase the previous one.
Here is my code:
let cvs = document.getElementById("canvas");
let ctx = cvs.getContext('2d');
let firstpos = 400;
let blocks = [];
blocks[0] = {
x: 400,
y: Math.floor(Math.random() * 360)
}
function draw() {
for (var i = 0; i < blocks.length; i++) {
ctx.beginPath()
ctx.fillStyle = "white";
ctx.fillRect(blocks[i].x, 0, 70, blocks[i].y);
ctx.fill();
blocks[i].x -= 0;
}
requestAnimationFrame(draw);
}
draw()
#canvas {
background-color: #000;
}
<canvas id="canvas" width="1000" height="500"></canvas>
Working snippet
Take advantage of CanvasRenderingContext2D.clearRect()
let cvs = document.getElementById("canvas");
let ctx = cvs.getContext('2d');
let firstpos = 400;
let blocks = [];
blocks[0] = {
x: 0,
y: Math.floor(Math.random() * 360)
}
function draw() {
blocks[0].x++;
ctx.clearRect(0, 0, canvas.width, canvas.height); // canvas clear up
for (var i = 0; i < blocks.length; i++) {
ctx.beginPath()
ctx.fillStyle = "white";
ctx.fillRect(blocks[i].x, 0, 70, blocks[i].y);
ctx.fill();
blocks[i].x -= 0;
}
requestAnimationFrame(draw);
}
setInterval(draw, 500)
#canvas {
background-color: #000;
}
<canvas id="canvas" width="1000" height="500"></canvas>
It's not possible to "undraw" something in canvas. However, you can clear the canvas on each frame with clearRect and re-draw everything in a new position.
Additionally, the current code uses blocks[i].x -= 0; which won't change the animation state even with a clear and redraw.
Parameters to fillRect appear incorrect or mislabeled. ctx.fillRect(blocks[i].x, 0, 70, blocks[i].y); should be ctx.fillRect(blocks[i].x, blocks[i].y, width, height);. There's also no need for creating a path or calling fill for this method.
It's typical to encapsulate all data for a block inside the object. We need a color, speed and x/y/height/width.
Note that y: Math.floor(Math.random() * 360) can result in a height of zero.
Here's a simple example of moving a block on the canvas:
const cvs = document.getElementById("canvas");
cvs.width = innerWidth;
cvs.height = innerHeight;
const ctx = cvs.getContext("2d");
const blocks = [{
x: innerWidth - 50,
y: 20,
velocityX: -1,
width: 50,
height: 50,
color: "white"
}];
(function draw() {
ctx.clearRect(0, 0, cvs.width, cvs.height);
for (const block of blocks) {
ctx.fillStyle = block.color;
ctx.fillRect(block.x, block.y, block.width, block.height);
block.x += block.velocityX;
}
requestAnimationFrame(draw);
})();
#canvas {
background-color: #000;
}
<canvas id="canvas"></canvas>
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>
I am trying to create below canvas.
Image
my code is below. but I am having trouble to make the canvas look the like the screenshot above. can anyone help me then?
thanks though
<html>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
var canvas;
var canvasContext;
window.onload = function() {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
canvasContext.fillStyle = 'blue';
canvasContext.fillRect(0,0,canvas.width,canvas.height);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(355,350,120,90);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(190,350,120,90);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(520,350,120,90);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(355,200,120,90);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(190,200,120,90);
canvasContext.fillStyle = 'grey';
canvasContext.fillRect(520,200,120,90);
}
</script>
</html>
.fillRect creates a filled region of color. However, .rect creates a "shape" that you can then use the .fill() and .stroke() methods upon.
In the below example if converted creation into a loop for brevity
var canvas;
var canvasContext;
window.onload = function() {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
canvasContext.fillStyle = 'blue';
canvasContext.fillRect(0,0,canvas.width,canvas.height);
var height = 90;
var width = 120;
var leftOffset = 190;
var topOffset = 200;
for(var x = 0; x < 6; x++){
canvasContext.beginPath();
canvasContext.rect(leftOffset,topOffset,width,height);
canvasContext.fillStyle = 'grey';
canvasContext.fill();
canvasContext.lineWidth = 4;
canvasContext.strokeStyle = 'lightblue';
canvasContext.stroke();
leftOffset += 165;
if(x === 2){
leftOffset = 190;
topOffset = 350;
}
}
}
JSFIDDLE
This tutorial on HTML5 Canvas rectangles is very handy
To add the text, you would append the following after (or before) the rect creating loop
canvasContext.beginPath();
canvasContext.font = '20pt Arial';
canvasContext.textAlign = 'center';
canvasContext.fillStyle = 'white';
canvasContext.shadowColor = 'black';
canvasContext.shadowOffsetX = 4;
canvasContext.shadowOffsetY = 4;
canvasContext.fillText('CHOOSE A SCENE TO COLOR', canvas.width/2,55);
UPDATED FIDDLE
Tutorials for text align, text shadow, and text.
Try something like this, use a function to draw a rectangle with exactly the border you want. The trick is to use .rect instead of fillRect so that you can use .stroke() immediately after.
<html>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
function draw_bordered_rect(context, x, y, w, h) {
context.rect(x, y, w, h);
context.fillStyle = "grey";
context.fill();
context.lineWidth = 3;
context.strokeStyle = "lightblue";
context.stroke();
}
window.onload = function() {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
canvasContext.fillStyle = 'blue';
canvasContext.fillRect(0, 0, canvas.width, canvas.height);
canvasContext.font = '25pt Arial';
canvasContext.textAlign = 'center';
//drop shadow 2px to the left and 2px below the white text
canvasContext.fillStyle = "black";
canvasContext.fillText('CHOOSE A SCENE TO COLOR', canvas.width/2-2, 82);
//actual text ontop of the drop shadow text
canvasContext.fillStyle = 'white';
canvasContext.fillText('CHOOSE A SCENE TO COLOR', canvas.width/2, 80);
draw_bordered_rect(canvasContext, 355, 350, 120, 90);
draw_bordered_rect(canvasContext, 190, 350, 120, 90);
draw_bordered_rect(canvasContext, 520, 350, 120, 90);
draw_bordered_rect(canvasContext, 355, 200, 120, 90);
draw_bordered_rect(canvasContext, 190, 200, 120, 90);
draw_bordered_rect(canvasContext, 520, 200, 120, 90);
}
</script>
</html>
Looks like:
I have some code to design canvas box in HTML5. I think you should try this one, I hope it will help you to design your canvas box. I think you should use JavaScript mehtod context.fillRect as i am giving you Js Fidler Lind here
HTML Code
<canvas id="myCanvas" width="500" height="400">
<!-- Insert fallback content here -->
</canvas>
JavaScript Code
var canvas = $("#myCanvas");
var context = canvas.get(0).getContext("2d");
// Set rectangle and corner values
var rectX = 50;
var rectY = 50;
var rectWidth = 100;
var rectHeight = 100;
var cornerRadius = 20;
// Reference rectangle without rounding, for size comparison
context.fillRect(200, 50, rectWidth, rectHeight);
// Set faux rounded corners
context.lineJoin = "round";
context.lineWidth = cornerRadius;
// Change origin and dimensions to match true size (a stroke makes the shape a bit larger)
context.strokeRect(rectX+(cornerRadius/2), rectY+(cornerRadius/2), rectWidth-cornerRadius, rectHeight-cornerRadius);
context.fillRect(rectX+(cornerRadius/2), rectY+(cornerRadius/2), rectWidth-cornerRadius, rectHeight-cornerRadius);
// You can do the same thing with paths, like this triangle
// Remember that a stroke will make the shape a bit larger so you'll need to fiddle with the
// coordinates to get the correct dimensions.
context.beginPath();
context.moveTo(400, 60);
context.lineTo(440, 140);
context.lineTo(360, 140);
context.closePath();
context.stroke();
context.fill();
This javascript code will design canvas box just like below g]iven image
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);
I'm trying to move something on the canvas upon pressing the left key.
$(document).ready(function () {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.onload = function(){
ctx.drawImage(img,0,0); // draw the image at the right coords
ctx.drawImage(img,110,110); // draw the image at the right coords
ctx.save();
};
img.src = 'tiles/processed/1_grass.png'; // Set source path
function draw() {
ctx.translate(20,0);
};
draw();
draw();
draw();
$(document).keydown(function(e) {
if (e.keyCode == 37) {
draw();
};
});
});
Now, it appears the three draw();'s work, but the one inside the function doesn't.
Am I totally missing the concept of canvas (in that it is static by nature, and has to be entirely re-drawn all the time) or is there something I'm doing wrong?
(ps.: I'm using Jquery as well)
Cheers!
You're never actually redrawing the canvas. You draw once (img.onload) and otherwise only translate the canvas.
Your draw function should clear the canvas and redraw the image.
here is a simple example, building on your code:
$(function () {
var ctx = document.getElementById('canvas').getContext('2d');
function draw() {
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.restore();
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, 20, 20);
};
draw();
$(document).keydown(function(evt) {
switch(evt.keyCode) {
case 37:
ctx.translate(-5, 0);
break;
case 38:
ctx.translate(0, -5);
break;
case 39:
ctx.translate(5, 0);
break;
case 40:
ctx.translate(0, 5);
break;
}
draw();
});
});
demo: http://jsfiddle.net/Vx2kQ/
Personally, though, I would not use translate to handle that movement. I would use some x/y coords, stored in a private variable. On keydown I would then manipulate those coords and redraw.