How to add image to canvas using fabric js - javascript

I am trying to add images to canvas using fabric.js. I want to add a image every time the button is clicked. The image is stored in my computer. When the image is added to the canvas, I would like to be able to drag it over the canvas.
Here is my javascript code:
function addimage1() {
var canvas = new fabric.Canvas('c');
var img = document.createElement("img");
img.src = url_1;
img.height = 50;
img.width = 100;
//optionally set a css class on the image
// var class_name = "foo";
// img.setAttribute("class", class_name);
var imgInstance = new fabric.Image(img, {
left: 100,
top: 100,
angle: 30,
opacity: 0.85
});
canvas.add(imgInstance);
//document.getElementById("resizable").appendChild(img);
//document.body.appendChild(img);
}
and here is the html code for button and canvas:
<div class="description">
<canvas id="c" width="710" height="600" style="background-color: #ffffff" ></canvas>
</div>
What am I doing wrong so the image wont be displayed?

Related

How do I embed an image on a canvas (HTML/JS)

I am trying to embed an image into a canvas so that I can draw lines over the image with the canvas. However, I can't seem to get the image to appear inside the canvas. Here's the code I have (HTML then JS):
<canvas id="myCanvas" style="border:1px solid #d3d3d3; position: relative; z-index:3; top:10em; width: 30em; height: 20em; left: 22em;"></canvas>
<img src="mapfinal.png" id="mapPic" style="display: none;"/>
javascript
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var map = document.getElementById("mapPic");
ctx.drawImage(map, 20, 20);
Thank you so much for any help!
It could be one of two things. The most likely issue is that the image is not yet loaded before you try to draw it. To fix this, add an onload event listener to the img element to draw it once the image has loaded.
<img src="mapfinal.png" id="mapPic" onload="drawCanvas" style="display: none;"/>
<script>
function drawCanvas() {
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var map = document.getElementById("mapPic");
ctx.drawImage(map, 20, 20);
}
</script>
The other issue might be that since the img element is set to display: none the browser isn't loading the image at all. Depending on the browser it may or may not load it. If you don't want the image to dispaly a better approach would be to create it through JavaScript.
var map = new Image();
map.onload = function() {
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.drawImage(map, 20, 20);
};
map.src = 'mapfinal.png';

Add image to fabric js canvas from Blob or base64 img src

I'm sorry if I'm asking the question wrong.
I converted a canvas to an image, and I have the image hidden on a page with a class of imgSrc
The src from the canvas image returns a base64 object
<img class="imgSrc" src="data:image/png;base64,ifsdfjdjkdjf;sfjjfskfdjdf">
I get the error
Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type
when trying to add an image to the canvas using Fabric js
var canvas = this.__canvas = new fabric.StaticCanvas('canvas1');
var imgElement = document.getElementsByClassName('imgBox');
var imgInstance = new fabric.Image(imgElement, {
left: 100,
top: 100,
height: 30,
width: 30
});
canvas.add(imgInstance);
Do I suppose to do some sort of conversation first with the image src ?
getElementsByClassName returns node list,get the first element by list[0], and create image object.
DEMO
var canvas = new fabric.Canvas('canvas');
var imgElement = document.getElementsByClassName('imgSrc')[0];
var imgInstance = new fabric.Image(imgElement, {
left: 100,
top: 100,
scaleX: 200/imgElement.width,
scaleY: 200/imgElement.height
});
canvas.add(imgInstance);
canvas {
border: 1px solid #999;
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<img class='imgSrc' src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFAAAABQBAMAAAB8P++eAAAAMFBMVEX////7+/vr6+vNzc2qqqplywBWrQD/Y5T/JTf+AADmAABeeEQvNydqAAAGBAMAAAGoF14oAAAEBUlEQVR42u2WTUwUVxzA/2925LIojsyqCLtMqSQeFJeFROPHstjdNkZdkaiX9mRTovYgSYNFE43Rg5IeNG5SqyaVcGzXkvTm7hZWq9bKriAYYzSLBI3WAplp0jY2kV3fzPuYGcBxD/bmO0zevPeb//f7v0FQ5EDvwf8LFG89ixYDol9Wo+smKal2sHF6kM6q7qbE5tY03d7SHR6ygiuvwY1txkzIlPaD3NQ4Zryk/PCP1wKibBlI97dq+idXUxqgcEkVnruS/smRpuWaCbrHU5pc/wyTQsata0U77wVBTlRP9UNkT9oE61K9AHL9VERbeTVurMjNm54mqrFw8CwKmWBfpf6V2Dx/TdxN3YjMf2JwIEZ8JnjnEbEjvLAQZ1EKlxkciJ9UcdD1Z5ztDmgsgPIrMkWtMgfd41xOYXZOIjUcLB3tdchypHWIgb5k2gH0nE0zMHjRCRTLWxgY/VQrDuybcAQ/DDEwmwEn8COlSDBcTUE0GXcEjRzqoDDhDH7sfccg2szAt9hogjBFQFRmDyd9N1VTEFegXXKEVKQFJHEUd0DSKhLthIm0HSQpnNdCNizgq147GP0m7QTygNMye6NqM9ekwlG4kLI5I4cMZ+bVhMA8MwX1rw9oIjakAYX6jXlBRRJ4BF6PwmRSfQyLFhJwWy/IG8khKuirljODG0DfGAd3qCBNEol5vCqFAxqYLeUyB0H2A2Q0DspRD3BQfJEc5KBl6KprG6pNEPqqfkKzOQBsha2bQeVw6g3nSySaGYgb99ylhsLDLVYQ3E+oozOGHKzVbCBs+HkuUm6ivd4E0ZYeNTPTTrn51+0wA9TJgpZVLeaV1y+4yS8c64W0/AcFTBCHK/fFEMwFAmo4KRldE0ZxsF8cGbTuzYqHtOz8t6e8TMk5CcjNSC+kdcfgPyag9AoDhUQARmvAcIiAW3v0JzWJg64BJXdBQ21+/b4zwMqRW5dA2h3I7+onYJd+Y4i3FbyMxz4hxE7hS2MBdSq6Fgq6Bny/dxv6Sk76COj6Yz91ZG8dToQ7oYNCqu4QjX9FK5UoPt/PXO701mruhwcxGP2ecahzzxBtUtlzLHclsXtBA6wc+a2brlUc8TCvg5cPM7LiaOPT8Y4ub3bpAbqy+MQ18xRmvIe5nr83YXDt8Nca0/GveWniSHByybEVwx1dD1ccYB/6yF8DTaGcYLFA391o6DjjohaWfKXQ/xCWazmhPDhNbYf2WH4fse9zhRUkLwrXlUD+9iVD5HR77KWheclxkqsZ1bM+pqcWZ2xVe0zXjPb6pyO8IK1l5trcA7mLKuo48+VpQG0BuPmZeTbs9Vi+9oQyqv6Ieyou4FybU+HqRS4o+TH1VG7MvgFFjvfguwFfA4FobmCxcnTPAAAAAElFTkSuQmCC"/>
<canvas id="canvas" width="400" height="400"></canvas>

Why is the image from my canvas getting downloaded without the text overlay?

Requirement:
Users can type in text that goes as an overlay on top of an image.
Users can download the image with the overlay.
To do this, I'm drawing the image onto the canvas, filling with the text and then setting the link's href to the canvas's dataURL.
Findings:
I can see the text overlay on the image in the canvas just fine.
If I right-click on the canvas and download the image, I can see the text overlay just fine.
If I click on the link, I see the original image without the text overlay.
What did I miss?
Here's the snippet:
var imgURL = 'https://upload.wikimedia.org/wikipedia/commons/5/56/Neptune_Full.jpg';
function loadCanvas(dataURL) {
var canGreeting = document.getElementById('canGreeting');
var context = canGreeting.getContext('2d');
// load image from data url
var imageObj = new Image();
imageObj.crossOrigin = 'anonymous';
imageObj.onload = function() {
context.drawImage(imageObj, 0, 0);
context.font = "20px sans-serif";
context.fillStyle = "#FFFFFF";
var arrayOfLines = $('#txtGreetingText').val().split('\n');
var y = 50;
var i = 0;
$(arrayOfLines).each(function() {
context.fillText(arrayOfLines[i], 50, y);
i++;
y += 30;
});
};
imageObj.src = dataURL;
lnkDownload.download = "card.jpg";
lnkDownload.href = imageObj.src;
}
$(document).ready(function() {
loadCanvas(imgURL);
$("#txtGreetingText").on("keydown", function(e) {
loadCanvas(imgURL);
});
});
textarea {
width: 420px;
height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea name="txtGreetingText" id="txtGreetingText"></textarea>
<br/>
<canvas id="canGreeting" width="480" height="480"></canvas>
<br/>
<a id="lnkDownload">Download this card</a>
href attribute should be pointing to base64 encoded image of the canvas source. Do this:
$(arrayOfLines).each(function() {
context.fillText(arrayOfLines[i], 50, y);
i++;
y += 30;
});
// udpate link to image
// Grab base64 encoded URL
var url = canGreeting.toDataURL("image/png;base64;");
lnkDownload.href = url;

Canvas wont display image inside of it

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<canvas id="spriteCanvas" width="500" height="500">
<img id="coin" width="440" height="40" src="coin.png">
</canvas>
</body>
</html>
I tried placing an image inside a canvas element, but it won't display on the browser. I know the image tag works because it's displayed if I place it outside of the canvas element. Also, if I inspect the canvas element, I can see that the image is inside, but its dimensions are 0 by 0. Can somebody explain why this isn't working?
EDIT: My original code added the image through javascript, but it wouldn't show on the canvas. It was giving me the same problems as above. But I just realized I was missing "onload".
original code:
var coinImage = new Image();
coinImage.src = "coin.png";
var sCanvas = document.getElementById('spriteCanvas');
function Sprite(canvas, width, height, image){
this.context = canvas.getContext("2d");
this.width = width;
this.height = height;
this.image = image;
}
Sprite.prototype.render = function() {
var that = this;
this.context.drawImage(that.image, 0, 0);
}
function init() {
var coin = new Sprite(sCanvas, 100, 100, coinImage);
coin.render();
}
init();
editted code:
var coinImage = new Image();
coinImage.src = "coin.png";
var sCanvas = document.getElementById('spriteCanvas');
function Sprite(canvas, width, height, image){
this.context = canvas.getContext("2d");
this.width = width;
this.height = height;
this.image = image;
}
Sprite.prototype.render = function() {
var that = this;
this.context.drawImage(that.image, 0, 0);
}
coinImage.onload = function () {
var coin = new Sprite(sCanvas, 100, 100, coinImage);
coin.render();
}
This isn't how a <canvas> tag works. If you want your image to appear in your canvas, you will have to use JavaScript to place the pixels of the image into your canvas.
<canvas>s are exactly what they state: canvases. They are an element for you to draw on programmatically. If you just want to display an image on a page, you don't need a canvas, you just need the <img> tag. In fact, elements should not be placed in <canvas>.
Take a look at CanvasRenderingContext2D.drawImage() and this tutorial: HTML5 Canvas Image Tutorial.
And this snippet:
var canvas = document.getElementById("painting"),
ctx = canvas.getContext("2d"),
image = new Image();
image.onload = function() {
ctx.drawImage(image, 30, 50);
};
image.src = "http://cdn.sstatic.net/Sites/stackoverflow/img/sprites.png?v=10a9e8743fb0";
<canvas id="painting" width="300" height="300"></canvas>
To draw an image on a canvas, use the following method:
drawImage(image,x,y)
If the image you want to draw is not in the DOM already you can load an image directly from a URL with a few lines of javascript.
function loadAndDrawImage(url)
{
// Create an image object. This is not attached to the DOM and is not part of the page.
var image = new Image();
// When the image has loaded, draw it to the canvas
image.onload = function()
{
// draw image...
}
// Now set the source of the image that we want to load
image.src = url;
}
loadAndDrawImage("http://www---.png");

Any way to achieve CSS 3D transform with javascript?

I want to rotate an image in 3D and this is possible in css with
transform: perspective(50px) rotateX(10deg) rotateY(10deg) rotateZ(10deg);
Currently I am using a canvas and the .style.transform property does not work for me. Example: https://jsfiddle.net/chung9ey/31/ . Note: I don't want to have a css file or style tags at all.
Your code is basically correct, but instead of img.style.transform, transform the canvas with canvas.style.transform:
var img = new Image;
var canvas = document.getElementById("hello");
var context = canvas.getContext("2d");
img.onload = function(){
canvas.style.transform = "perspective(50px) rotateX(10deg) rotateY(10deg) rotateZ(10deg)";
context.drawImage(img, 0 ,0, 500, 300);
}
img.src = "https://www.enterprise.com/content/dam/global-vehicle-images/cars/CHRY_200_2015.png";
<canvas id = "hello" width = "500px" height = "300px" style="border: 1px solid BLACK";></canvas>

Categories

Resources