add image on canvas on button click using fabric.js - javascript

I am trying to add images on button click on canvas. . By default there is 1 image on canvas. Images are getting added on button click, But all images are erased when i click on canvas. Only the background image remains constant.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://code.jquery.com/jquery-1.10.1.js"></script>
<script src="fabric.js"></script>
</script>
<script>
function fun(){
var canvas = window.canvas = new fabric.Canvas('c');
fabric.Image.fromURL('compress/a.jpg', function(img){
canvas.add(img.scale(0.1).set({ left: 150, top: 200, angle: 20 }));
});
$(canvas.wrapperEl).on('mousewheel', function(e) {
var target = canvas.findTarget(e);
var delta = e.originalEvent.wheelDelta / 120;
if (target) {
target.scaleX += delta;
target.scaleY += delta;
// constrain
if (target.scaleX < 0.1) {
target.scaleX = 0.1;
target.scaleY = 0.1;
}
// constrain
if (target.scaleX > 10) {
target.scaleX = 10;
target.scaleY = 10;
}
target.setCoords();
canvas.renderAll();
return false;
}
});
}
function add()
{
window.canvas = new fabric.Canvas('c');
window.canvas.getObjects();
fabric.Image.fromURL('compress/b.jpg', function(img){
window.canvas.add(img.scale(0.1).set({ left: 150, top: 200, angle: 20 }));
window.canvas.selection = true;
window.canvas.renderAll();
window.canvas.calcOffset();
});
}
</script>
<style>
canvas {
border: 1px solid #999;
}
</style>
</head>
<body onload=fun()>
<div id="test" align="center" style="display: block">
<canvas id="c" width="600" height="600"></canvas>
</div>
<button id="but" onclick="add()">add images</button>
</body>
</html>
Please help me with this code

try using canvas.clear() before adding

Related

Canvas duplicates multiple shapes

I want to add 10 to the position of the ball, but it adds position to the duplicated shape. I tried to make a separate function but it did not work.
HTML5 Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<canvas id="Game" width="800" height="600" style="border: 1px solid #d3d3d3;
background-color: #f1f1f1;"></canvas>
<script src="Game.js"></script>
</body>
</html>
Javascript Code:
var GameCanvas = GameCanvas = document.getElementById("Game");
var GameCtx = GameCtx = GameCanvas.getContext("2d");;
var BallSprite = 50;
window.onload = function () {
setInterval(HoldSprites, 100);
}
function HoldSprites() {
BallSprite = BallSprite + 10;
GameCtx.beginPath();
GameCtx.arc(BallSprite, 50, 40, 0, 2 * Math.PI);
GameCtx.stroke();
}

Alter an image's position based on a key that is pressed?

The code here should take the element and move it to the left or right. However, the image is still in place.
var posX = 100;
document.getElementById("ship").addEventListener("keydown", moveShip);
function moveShip(event) {
if (event.key == "ArrowLeft") {
posX -= 2;
} else if (event.key == "ArrowRight") {
posX += 2;
}
}
HTML of the code is very basic, nothing much has been added here
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<title>ship</title>
</head>
<body>
<img id="ship" src="spaceship.png" />
<canvas id="myCanvas"></canvas>
<script src="extensions.js"></script>
<script src="main.js"></script>
</body>
</html>
The CSS of the code is here
canvas{
border: 1px, solid, black;
}
html{
background-color: black;
}
#ship{
width: 100px;
}
You should give the image a relative position and set the left CSS property to move it.
<img id="ship" src="spaceship.png" style="position: relative;"/>
<script>
var posX = 100;
var ship = document.getElementById("ship");
ship.style.left = posX;
ship.addEventListener("keydown", moveShip);
function moveShip(event) {
if (event.key == "ArrowLeft") {
posX -= 2;
} else if (event.key == "ArrowRight") {
posX += 2;
}
ship.style.left = posX;
}
</script>

Why doesn't context.drawImage() work in html canvas?

I'm trying to put the image file "sticky.png" into a canvas box, but all I'm getting is a blank canvas. Can anyone point out what I'm doing wrong and/or give me code that works?
<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #000000;">
</canvas>
<body>
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var sticky = new Image();
sticky.onload = function() {
context.drawImage(sticky, 0, 0);
sticky.src = "sticky.png";
};
</script>
</body>
You need to include the sticky.src before sticky.onload.
<body>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;"></canvas>
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var sticky = new Image();
sticky.src = "sticky.png";
sticky.onload = function() {
context.drawImage(sticky, 0, 0);
};
</script>
</body>
Fiddle
sometimes as a workAround we have to load the image before the canvas. It's very unusual, but it WORKS. And then you just hide the image. Don't forget to use setTimeOut to wait till image is loaded!
setTimeout("paintStar()", 2000);
function paintStar() {
var canva3 = document.getElementById('canvas3');
canva3.width = 640;
canva3.height = 480;
var ct3 = canva3.getContext('2d');
var img = new Image();
img.src = 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ3DlDGTyfaFMtUf9GYykLglqfS8GzHbeKRV5vDfHraV1ihNIYo';
ct3.drawImage(img, 0, 0);
ct3.drawImage(img, 0, 0, 20, 20, 10, 200, 20, 20);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CANVAS</title>
<style>
.canvas-1 {
width: 640px;
height: 480px;
border: 1px solid #777;
}
.img-1 {
display: none;
}
</style>
<script src="canva3.js" defer></script>
</head>
<body>
<div class="img-1"><img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ3DlDGTyfaFMtUf9GYykLglqfS8GzHbeKRV5vDfHraV1ihNIYo" alt=""></div>
<canvas id="canvas3" style="border: 2px solid #444;">Doesn't work!</canvas>
</body>
</html>

Javascript, displaying a transparent image.

<!DOCTYPE html>
<html>
<head>
<style>
#container {
width: 320px;
height: 480px;
border: 1px solid red;
}
</style>
</head>
<body>
<div style="position: relative;" id="container">
<canvas id="myCanvas" width="320" height="480"
style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
<canvas id="plane" width="320" height="480"
style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
<canvas id="canvas2" width="100" height="100"
style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>
<img id="scream" src="http://4.bp.blogspot.com/-BrJHwoqM2qg/Uq94Il8t-1I/AAAAAAAAD7s/vyFLZUgMkdA/s1600/Plane.png" alt="The Scream" width="0" height="0">
<script>
var c=document.getElementById("myCanvas");
var c2=document.getElementById("canvas2");
var c3=document.getElementById("plane");
var plane;
var ground;
var score1 = "1"
var score = score1;
var increase = 6;
var delay = 40;
var scorez;
start();
function start(){
backgrounds();
planeDraw();
var scorez = setInterval(scoring, delay);
}
function backgrounds(){
var ctx=c.getContext("2d");
var my_gradient=ctx.createLinearGradient(0,0,0, 280);
my_gradient.addColorStop(0,"white");
my_gradient.addColorStop(1,"blue");
ctx.fillStyle=my_gradient;
ctx.fillRect(0,0,320,480);
ground = c.getContext("2d");
ctx.fillStyle="black";
ctx.fillRect(0,450 , 320 ,30);
}
function scoring(){
scores();
score2();
}
function scores(){
score -= 3-(3+increase);
}
function score2(){
//var canvas = document.getElementById('canvas2');
var context = c2.getContext('2d');
context.clearRect(0, 0, c2.width, c2.height);
var w = c2.width;
c2.width = 1;
c2.width = w;
var text=c2.getContext("2d");
text.font="20px Georgia";
text.fillText(score ,15,20);
}
function hit(){
}
function loes(){
clearInterval(scorez);
}
function planeDraw(){
plane = c3.getContext('2d');
var img = new Image();
img.src = "http://4.bp.blogspot.com/-BrJHwoqM2qg/Uq94Il8t-1I/AAAAAAAAD7s/vyFLZUgMkdA/s1600/Plane.png"; //transparent png
plane.drawImage(img, 0, 0, 320, 100);
}
</script>
<!--
http://4.bp.blogspot.com/-BrJHwoqM2qg/Uq94Il8t-1I/AAAAAAAAD7s/vyFLZUgMkdA/s1600/Plane.png
--!>
</body>
</html>
All the code seems to be working fine, the only issue I am finding is the image of the plane is not printing. Could some one please tell me what I am doing wrong. Thank you.
When I changed the planeDraw function to create a rectangle it worked perfectly. As well as this the code worked in JSFiddle, when it was isolated.
You are drawing the image before it has loaded.
Load the plane image once, and draw it after its onload event has fired.
If you can, consider embedding the image as a data: URL, as this will remove the need for waiting for the image to load, however keep in mind that it makes your code bigger!
You have to wait for the image to load before drawing it.
Try:
img.onload = function()
{
plane.drawImage(img, 0, 0, 320, 100);
};
img.src = "http://4.bp.blogspot.com/-BrJHwoqM2qg/Uq94Il8t-1I/AAAAAAAAD7s/vyFLZUgMkdA/s1600/Plane.png"; //transparent png
It's best to define the onload function before setting the src attribute - depending on the browser, if the image file is in your cache, the onload event may fire as soon as the src is set (before you have a chance to define onload).

How do I call a JavaScript function every 60 seconds?

So I'm trying to work on a Canvas demo, and I want this square to move from one side to the other, but I can't figure out how to call JavaScript in a way that repeats every 60 seconds.
Here's what I got so far:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Canvas test</title>
<meta charset="utf-8" />
<link href="/bms/style.css" rel="stylesheet" />
<style>
body { text-align: center; background-color: #000000;}
canvas{ background-color: #ffffff;}
</style>
<script type="text/javascript">
var x = 50;
var y = 250;
function update(){
draw();
x = x + 5;
}
function draw(){
var canvas = document.getElementById('screen1');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgb(236,138,68)';
ctx.fillRect(x,y,24,24);
}
}
</script>
</head>
<body onLoad="setTimeout(update(), 0);">
<canvas id="screen1" width="500" height="500"></canvas>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Canvas test</title>
<meta charset="utf-8" />
<link href="/bms/style.css" rel="stylesheet" />
<style>
body { text-align: center; background-color: #000000;}
canvas{ background-color: #ffffff;}
</style>
</head>
<body>
<canvas id="screen1" width="500" height="500"></canvas>
<script type="text/javascript">
var x = 50;
var y = 250;
function update(){
draw();
x = x + 5;
}
function draw(){
var canvas = document.getElementById('screen1');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgb(236,138,68)';
ctx.fillRect(x,y,24,24);
}
}
update();
setInterval ( update, 60000 );
</script>
</body>
</html>
1000ms = 1 second, 60000 = 60 seconds.
Using setTimeout, instead of setInterval, allows you to stop the animation with clearTimeout and the use of a variable.
(edit: this whole thing doesn't work in IE, but the setTimeout - clearTimeout combo itself should... also changed the onload and onclick events)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Canvas test</title>
<meta charset="utf-8" />
<link href="/bms/style.css" rel="stylesheet" />
<style>
body { text-align: center; background-color: #000000;}
canvas{ background-color: #ffffff;}
</style>
<script type="text/javascript">
var x = 50;
var y = 250;
function update()
{
draw();
x = x + 5;
// For one minute, you would use 60000 instead of 100.
// 100 is so you can actually see it move.
myToggle = setTimeout(update, 100);
};
function draw()
{
var canvas = document.getElementById('screen1');
if (canvas.getContext)
{
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgb(236,138,68)';
ctx.fillRect(x,y,24,24);
}
};
function stop()
{
clearTimeout(myToggle);
};
window.onload = function()
{
document.getElementById("stop").onclick = function() { stop(); };
document.getElementById("start").onclick = function() { update(); };
update();
};
</script>
</head>
<body>
<canvas id="screen1" width="500" height="500"></canvas><br/>
<input id="stop" type="button" value="Stop" /><br/>
<input id="start" type="button" value="Start" />
</body>
</html>

Categories

Resources