Image animate function not working in fabric js? - javascript

I am using fabric js for canvas animation and I am created canvas with id 'canvas' then put image in it and set left position to zero. It's working fine but animate function is not working.
Please help me.
My code:
HTML:
<canvas id="canvas" width="990" height="285">
This text is displayed if your browser
does not support HTML5 Canvas.
</canvas>
javascript:
var canvas = new fabric.Canvas('canvas');
var image = new Image();
image.src = 'images/body.png';
var bugBody = fabric.Image.fromURL(image.src, function (oImg) {
canvas.add(oImg);
oImg.set('left',0)
});
bugBody.animate('left', 200, {
onChange: canvas.renderAll.bind(canvas)
});
Thanking You.

I think that this happen because your image is not complete loaded.
So, you can put your animation code inside your callback function.
Check this jsfiddle: http://jsfiddle.net/9x9Qc/
Like this:
var srcImg = "http://fabricjs.com/lib/pug.jpg";
// canvas
var canvas = new fabric.Canvas('c');
fabric.Image.fromURL(srcImg, function (oImg) {
canvas.add(oImg);
oImg.set('left',0);
oImg.set('top', 100);
oImg.scale(.25);
canvas.renderAll();
// and then, we can animate the image
oImg.animate('left', 200, {
onChange: canvas.renderAll.bind(canvas)
});
});

Related

Set background image for Fabric Canvas dynamically

I want to add draw shapes on a Image, so decided to use Fabric JS. I am able to get all shapes and objects working well. Now How do I background set exactly to Image. The Image is dynamic, I want to draw on top of that image, and basically store the annotations of objects for backend processing.
Existing solution using Canvas
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d");
canvas.width = 903;
canvas.height = 657;
var background = new Image();
background.src = "http://www.samskirrow.com/background.png";
// Make sure the image is loaded first otherwise nothing will draw.
background.onload = function(){
ctx.drawImage(background,0,0);
}
Reference - https://stackoverflow.com/a/14013068/2094670
I like this solution.
Live Demo
My Current Fabric JS Code
// Initialize a simple canvas
var canvas = new fabric.Canvas("c", {
hoverCursor: 'pointer',
selection: true,
selectionBorderColor: 'green',
backgroundColor: null
});
// Define the URL where your background image is located
var imageUrl = "../dog.jpg";
// Define
canvas.setBackgroundImage(imageUrl, canvas.renderAll.bind(canvas), {
// Optionally add an opacity lvl to the image
backgroundImageOpacity: 0.5,
// should the image be resized to fit the container?
backgroundImageStretch: false
});
Html
<canvas id="c"></canvas>
Problem.
The image of dog is full hd image, however I see only portion of it. How to do render the background image to its actual height and width using Fabric Canvas ? Since Images are comming dynamically, I might not know exact height and width to hardcode it.
Here's the way to set canvas size base on image size via fabric.js.
It's done initiating the Fabric canvas inside the onload callback, that way we are able to get the image width and height, then set them into the setDimesions method.
img.onload = function () {
...
canvas.setDimensions({ width: img.width, height: img.height });
};
var imageUrl = "http://i.imgur.com/yf6d9SX.jpg";
var background = new Image();
background.src = imageUrl;
// wait for the image to load, then set Fabric Canvas on the callback that runs after image finishes loading
background.onload = function () {
var canvas = new fabric.Canvas("c", {
hoverCursor: "pointer",
selection: true,
selectionBorderColor: "green",
backgroundColor: null,
});
// set canvas width and height based on image size
canvas.setDimensions({ width: background.width, height: background.height });
canvas.setBackgroundImage(imageUrl, canvas.renderAll.bind(canvas), {
// Optionally add an opacity lvl to the image
backgroundImageOpacity: 0.5,
// should the image be resized to fit the container?
backgroundImageStretch: false,
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.1.0/fabric.min.js"></script>
<canvas id="c"></canvas>

MVC using image path for canvas on page with JavaScript

<canvas id="myCanvas" width ="320" height="260">
<img src="#Model.img.path" id="img" >
I am trying to use MVC model to create "update news" page.
News has an image and i am using canvas to upload images that because users can edit images with editor based on canvas process. Creating news is Ok.But when updating news, i would like to see image in my canvas that already created . i took my entity and pass it to the View of "update news"-news includes img path- but i cant figure out how can i use this path to show my image in the canvas element.
Thanks alredy.
Sorry for my english.
var img = new Image()
img.onload = function () {
ctx.drawImage(img, 0, 0, 1600, 900);
}
img.src = "#Model.image.path";
I just use this simple code. It works.
for drawing image in canvas with javascript , you can use this function:
function drawDataURIOnCanvas(strDataURI, canvas) {
"use strict";
var img = $("#img");
img.addEventListener("load", function () {
canvas.getContext("2d").drawImage(img, 0, 0);
});
}
for calling :
drawDataURIOnCanvas('#Model.img.path',$("#myCanvas"));

How to save Zoomed and Panned Canvas to dataUrl in Javascript

I build a canvas Element in which you can zoom and pan a background image and by click you can add Icons on it. It is built on fabric js.
So once I added icons and zoomed and panned, I would like to save the image to dataurl. If I just use canvas.toDataURL, I can only see the currently shown area. Does anybody have an Idea, how I can save the entire area of the background image with all elements on the canvas? I therefore need a function, which resets the zoom and the pan and adjusts the size of the canvas to the size of the background image.
I included an example of how initialized my canvas below.
// New Fabric Canvas
var canvas = new fabric.Canvas('c'); //render image to this canvas
window.addEventListener('resize', resizeCanvas, false);
function resizeCanvas() {
canvas.setHeight(window.innerHeight);
canvas.setWidth(window.innerWidth);
canvas.renderAll();
}
// resize on init
resizeCanvas();
// Load image
var image = new Image();
image.onload = function() {
loadImage(image, canvas);
canvas.height = image.height;
canvas.width = image.width;
}
function loadImage(image, canv) {
var img = new fabric.Image(image, {
selectable: false,
lockUniScaling: true,
centeredScaling: true,
alignX: "mid",
alignY: "mid",
});
canv.add(img);
canv.centerObject(img);
}
image.src = 'http://placehold.it/350x150';
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.1.0/fabric.all.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="canvasarea" style="background: #000;">
<canvas id='c' onclick="return false;"></canvas>
</div>
If you just want to generate an image and not change the zoom level of canvas, you can pass multiplier parameter to toDataUrl function.
var dataURL = canvas.toDataURL({
format: 'png',
multiplier: 2
});
This will generate an image after zooming in 200%.
You can even specify the part of the canvas, you want to generate an image of by using:
var dataURL = canvas.toDataURL({
format: 'png',
left: 100,
top: 100,
width: 200,
height: 200
});
Check the details here, toDataUrl function:
http://fabricjs.com/docs/fabric.Canvas.html

Image size enlarging when drawing it on the Canvas

I have a 46*46 png image . While I use the following code to draw it on the Canvas,the image is getting enlarged.
window.onload = function()
{
drawEx1();
}
var image1 = null;
function drawEx1()
{
image1 = new Image();
image1.src =
"unnamed.png";
image1.addEventListener('load', drawImage1);
}
function drawImage1()
{
if (image1.height > 46)
{
image1.height = 46;
}
context.drawImage(image1, 10, 10,image1.height,image1.height);
}
I have styled the CANVAS using a CSS for appearing it on the center of the browser.
What is it I'm doing wrong here. Please help. Thanks.
Don't use CSS to resize the canvas because it will distort the canvas content--stretching it.
Instead resize the canvas element itself:
<canvas width=100 height=100> or
document.getElementById('mycanvas').width=100;
Good luck with your project!

Javascript - image displaying over text

The code runs with no bugs, but a problem I am having is because the ".onLoad" function makes it display after the text has already been displayed on the screen. The problem I am facing is that I would like if the text (Loading graphics and loading variables) displayed over the image.
The code is here:
<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml1-transitional.dtd">
<html>
<body>
<canvas id="ctx" width="800" height="500" style="border:1px solid #d3d3d3;"></canvas>
<script>
var ctx = document.getElementById("ctx").getContext("2d");
var canvas = document.getElementById('ctx');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.onload = function(){
context.drawImage(imageObj,0,0);
};
imageObj.src = 'img/startscreen.jpg';
ctx.fillText('Loading variables.',50,50);
character=new Object();
character.hp=1;
character.name=null;
ctx.fillText('Loading graphics..',50,100);
</script>
</body>
</html>
I would layer the background image on its own canvas positioned behind the text layer. Then you can clear and update the text layer without having to re-draw the background image.
#background,#overlay {
position: absolute;
}
<canvas id="background"></canvas>
<canvas id="overlay"></canvas>
var can = document.getElementById('overlay'),
bg_can = document.getElementById('background'),
height = can.height = bg_can.height = 500,
width = can.width = bg_can.width = 500,
ctx = can.getContext('2d'),
bctx = bg_can.getContext('2d');
var img = new Image();
img.src = ' ... ';
img.onload = init;
function init() {
// draw the background
bctx.drawImage(this, 0, 0);
// draw your initial text
updateText('hello world');
// other stuff that is going to take time
updateText('done');
}
function updateText(msg) {
ctx.clearRect(0, 0, width, height);
ctx.fillText(msg, 50, 100);
}
This isn't very well thought out (my code example) for re-use purposes.. but I don't know much about your other needs :) hope this helps.
If you want to overlay String on image, why don you use image as backGround imange and place text over it??
Css
try in css
#ctx{
background-image:url('img/startscreen.jpg');}
remove image source in script or insert css in script itself
Css in scripts
ctx.style.backgroundImage=url('img/startscreen.jpg');
I called the function for the text to be displayed after the background has:
imageObj.src = 'img/startscreen.jpg';
imageObj.onload = function(){
context.drawImage(imageObj,0,0);
init()
};
function init(){
ctx.fillText('Loading variables.',50,50);
character=new Object();
character.hp=1;
character.name=null;
ctx.fillText('Loading graphics..',50,100);
}

Categories

Resources