Canvas - drawImage() after clearRect() - javascript

I have a problem. I am creating simple game in Canvas using JavaScript. Image doesn't display after call clearRect(), does anyone know, how to solve it?
var left1 = 0;
var context1 = document.getElementById('canvas1').getContext('2d');
render1();
function render1() {
var image = new Image();
image.onload = function () {
context1.drawImage(image, left1, 0, 200, 200);
};
image.src = 'http://www.pngall.com/wp-content/uploads/2016/06/Earth-Free-Download-PNG.png';
left1++;
requestAnimationFrame(render1);
}
var left2 = 0;
var context2 = document.getElementById('canvas2').getContext('2d');
render2();
function render2() {
context2.clearRect(0, 0, 500, 250);
var image = new Image();
image.onload = function () {
context2.drawImage(image, left2, 0, 200, 200);
};
image.src = 'http://www.pngall.com/wp-content/uploads/2016/06/Earth-Free-Download-PNG.png';
left2++;
requestAnimationFrame(render2);
}
canvas {
display: block;
}
It works, but old images are not deleted:
<canvas id="canvas1" height="250" width="500"></canvas>
It doesn't work, because of clearRect():
<canvas id="canvas2" height="250" width="500"></canvas>

if you try to animate your image , its not necessary to make two canvas instead use a timer , i hope this will help
`
var left1 = 0;
var context1 = document.getElementById('canvas1').getContext('2d');
var canvas1 = document.getElementById('canvas1');
window.onload = init;
function init() {
setInterval(drawc, 1000 / 60);
};
function drawc() {
if (left1 > canvas1.width) {
left1 = 0;
}
render1();
}
function render1() {
with(context1) {
clearRect(0, 0, canvas1.width, canvas1.height);
var image = new Image();
image.src = 'http://www.pngall.com/wp-content/uploads/2016/06/Earth-Free-Download-PNG.png';
beginPath();
drawImage(image, left1, 0, 200, 200);
closePath();
fill();
left1++;
// requestAnimationFrame(render1);
}
};

Related

Create smooth animation in canvas

I have a canvas object which is rendering an image. When the user click on button the image will move to right. My problem is this movement is not smooth. The image is simply jumping to the specified position. How can I make this movement smooth? This is the codepen example Can anyone please help me?
$(window).on('load', function () {
myCanvas();
});
function myCanvas() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var x = 0;
function fly() {
ctx.clearRect(0, 0, c.width, c.height);
ctx.closePath();
ctx.beginPath();
var img = new Image();
img.onload = function () {
ctx.drawImage(img, x, 0);
};
img.src = 'http://via.placeholder.com/200x200?text=first';
}
fly();
$('#movebutton').click(function () {
for (i = 0; i < 200; i++) {
x = i;
requestAnimationFrame(fly);
}
});
}
<canvas id="myCanvas" width="960" height="600"></canvas>
<button id="movebutton">Move</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
First of all, why are you loading your image in your frame rendering function - if cache is disabled, it will request an image every frame!
I rewrote the script so that the animation is linear and smooth, you can edit the speed variable to adjust the movement speed.
$(window).on('load', function () {
var img = new Image();
img.onload = function () {
myCanvas(img);
};
img.src = 'http://via.placeholder.com/200x200?text=first';
});
function myCanvas(img) {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var x = 0;
var last_ts = -1
var speed = 0.1
function renderScene() {
ctx.clearRect(0, 0, c.width, c.height);
ctx.closePath();
ctx.beginPath();
ctx.drawImage(img, x, 0);
}
function fly(ts) {
if(last_ts > 0) {
x += speed*(ts - last_ts)
}
last_ts = ts
if(x < 200) {
renderScene()
requestAnimationFrame(fly);
}
}
renderScene()
$('#movebutton').click(function () {
x = 0;
requestAnimationFrame(fly);
});
}

Drawing ends up all black

I'm trying to resize an image via HTML canvas, but when I display it, it displays all black.
My code
function onSuccess(imageData) {
var img = new Image();
img.src = imageData;
window.setTimeout(function() {
var maxSize = 200;
var canvas = document.createElement("canvas");
canvas.width = maxSize;
canvas.height = maxSize;
var ctx = canvas.getContext("2d");
ctx.drawImage(img.src, 0, 0, maxSize, maxSize);
dataurl = canvas.toDataURL("image/jpeg");
alert(dataurl);
}, 1000);
}
I'm not exactly sure what it is I'm doing incorrectly. Thanks for the help!

Why is a delay needed when drawing a image into a canvas?

Here is the code:
var spriteFolder = "../../assets/Painter/sprites/";
var sprites = {};
sprites.background = new Image();
sprites.background.src = spriteFolder + "spr_background.jpg";
sprites.cannon_barrel = new Image();
sprites.cannon_barrel.src = spriteFolder + "spr_cannon_barrel.png";
sprites.cannon_red = new Image();
sprites.cannon_red.src = spriteFolder + "spr_cannon_red.png";
sprites.cannon_green = new Image();
sprites.cannon_green.src = spriteFolder + "spr_cannon_green.png";
sprites.cannon_blue = new Image();
sprites.cannon_blue.src = spriteFolder + "spr_cannon_blue.png";
var Canvas2D = {
canvas: undefined,
canvasContext: undefined
};
Canvas2D.initialize = function(canvasName) {
Canvas2D.canvas = document.getElementById(canvasName);
Canvas2D.canvasContext = Canvas2D.canvas.getContext("2d");
};
Canvas2D.clear = function() {
Canvas2D.canvas.clearRect(0, 0, Canvas2D.canvas.width, Canvas2D.canvas.height);
};
Canvas2D.drawImage = function(sprite, position, rotation, origin) {
Canvas2D.canvasContext.save();
Canvas2D.canvasContext.translate(position.x, position.y);
Canvas2D.canvasContext.rotate(rotation);
Canvas2D.canvasContext.drawImage(sprite,
0, 0, sprite.width, sprite.height,
-origin.x, -origin.y, sprite.width, sprite.height
);
Canvas2D.canvasContext.restore();
};
function init() {
Canvas2D.initialize("myCanvas");
setTimeout(function() {
Canvas2D.canvasContext.drawImage(sprites.background, 0, 0);
}, 1000);
}
document.addEventListener("DOMContentLoaded", init);
If I don't use setTimeout, then the image is not drawn. Why?
Because your images were not yet loaded.
Thanks to your 1sec timeout they have enough time to load.
Have a look at this example from MDN https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images
You need to use similar approach - see img.onload()
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image();
img.onload = function(){
ctx.drawImage(img,0,0);
ctx.beginPath();
ctx.moveTo(30,96);
ctx.lineTo(70,66);
ctx.lineTo(103,76);
ctx.lineTo(170,15);
ctx.stroke();
};
img.src = 'https://mdn.mozillademos.org/files/5395/backdrop.png';
}

Animate image js

I have 2 images on canvas and i want to make imageObg to animate. Actually i want it to make a linear move to the right.I found a way to animate an object like a rectangle but i cant animate an image object that i use from another source.
Is there anyway that can i manage to do i? Does anyone knows?
window.onload = function() {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
var imageObj2 = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 69, 130);
};
imageObj2.onload = function() {
context.drawImage(imageObj2, 0, 0);
};
imageObj.src = 'http://imageshack.com/a/img745/822/pXDK5F.png'
imageObj2.src = 'http://i.dailymail.co.uk/i/pix/2014/09/04/1409790551890_wps_28_Astronaut_Reid_Wiseman_po.jpg'
};
body {
background-color: black
}
<div id='d1' style="position:absolute; top:80px; left:150px; z-index:1">
<canvas id='myCanvas' width='962' height='500' style="border:10px solid #ffffff;">
Your browser does not support HTML5 Canvas.
</canvas>
</div>
Just two things.
Set a periodically render routine using setInterval.
Set a move (or physics) routine, call it after each render.
window.onload = function() {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
var imageObj2 = new Image();
imageObj.src = 'http://imageshack.com/a/img745/822/pXDK5F.png'
imageObj2.src = 'http://i.dailymail.co.uk/i/pix/2014/09/04/1409790551890_wps_28_Astronaut_Reid_Wiseman_po.jpg'
window.setInterval(renderFrame, 50);
var ship = {
x: 69,
y: 130
};
function renderFrame() {
moveShip();
context.clearRect(0, 0, canvas.width, canvas.height);
if (imageObj.complete) {
context.drawImage(imageObj2, 0, 0);
}
if (imageObj.complete) {
context.drawImage(imageObj, ship.x, ship.y);
}
}
function moveShip() {
ship.x += 20;
if (ship.x > canvas.width) {
ship.x = 0 - imageObj.width;
ship.y = Math.random() * 250 + 50;
}
}
};
body {
background-color: black
}
<div id='d1' style="position:absolute; top:80px; left:150px; z-index:1">
<canvas id='myCanvas' width='962' height='500' style="border:10px solid #ffffff;">
Your browser does not support HTML5 Canvas.
</canvas>
</div>
Just increase the x position of the image with a setInterval command.
var img = document.createElement("IMG");
var img.src = [Image Source];
var x = 0;
window.setInterval(function() {
x ++;
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(img, x, 0);
}, 50);
Hope this helps.
Edit:
Here is a JSFiddle Example.

canvas image size in html5

var canvas = document.getElementById("canvasPnl");
var context = canvas.getContext('2d');
var locationtxt = "Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude;
var imageObj = new Image();
imageObj.src = document.getElementById("tempImg").src;
imageObj.onload = function () {
var x = 188;
var y = 30;
var width = 200;
var height = 137;
context.drawImage(imageObj, x, y, width, height);
context.font = "20pt Calibri";
context.fillText(locationtxt, 40, 40);
};
<canvas id="canvasPnl" width="132" height="120" style="border:0px solid #d3d3d3;"></canvas>
The size of the image is becoming bigger and it is not fitting in canvas and also the image is rotated.
How to get original image in canvas?
Ok, take a look at your reworked code below.
Notice "imageObj.src = document.getElementById("tempImg").src;" must go after imageObj.onload.
I have no access to your locationtxt or your tempImg, so I assume you are sure they are not the source of your problem.
This line of code will take an image of ANY size and force it to fit in your specified canvas size by scaling it. When it scales, you may get image distortion if your canvas size is not proportional to your image size.
context.drawImage(imageObj,0,0,imageObj.width,imageObj.height,0,0,canvas.width,canvas.height);
Here is your code -- just modified a bit :)
var canvas = document.getElementById("canvasPnl");
var context = canvas.getContext('2d');
var locationtxt = "Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude;
var imageObj = new Image();
imageObj.onload = function () {
context.drawImage(imageObj,0,0,imageObj.width,imageObj.height,0,0,canvas.width,canvas.height);
context.font = "20pt Calibri";
context.fillText(locationtxt, 40, 40);
};
imageObj.src = document.getElementById("tempImg").src;
<html>
<head>
<title></title>
</head>
<style type="text/css">
#mycanvas
{
border: 1px solid black;
}
</style>
<script type="text/javascript">
window.addEventListener('load', function () {
var img = new Image, ctx = document.getElementById('myCanvas').getContext('2d');
var img1=new Image;
img.src = 'ship.png';
img1.src='3D025.jpg';
img.addEventListener('load', function () {
var width = img.naturalWidth; // this will be 300
var height = img.naturalHeight; // this will be 400
var interval = setInterval(function() {
var x = 260, y = 0;
return function () {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.drawImage(img1, 0, y);
ctx.drawImage(img, x, 300,width,height);
x += 1;
if (x > ctx.canvas.width) {
x = 260;
width=width-10;
height=height-10;
ctx.drawImage(img, x, 300,width,height);
}
if (x == 750) {
x = 260;
}
};
}(), 1000/40);
}, false);
}, false);
</script>
<body>
<canvas id="myCanvas" height="600" width="1000"></canvas>
</body>
</html>

Categories