Draw image with transparent background on canvas - javascript

I need to draw an image with transparent background on canvas. I have a code that should do that:
var can = document.getElementById('canvasId');
var ctx = can.getContext('2d');
ctx.fillRect(50,50,500,500); // something in the background
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
img.src = "https://i.stack.imgur.com/7JXBD.png"; //transparent png
<canvas id="canvasId"></canvas>
But the background is not transparent:

Your code works perfectly - you just need an image with a transparent background - like this question mark:
var can = document.getElementById('canvasId');
var ctx = can.getContext('2d');
ctx.fillRect(50,50,500,500); // something in the background
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
img.src = "https://i.stack.imgur.com/RPEQQ.png"; //transparent png
<canvas id="canvasId"></canvas>
And to prove it's not just got a white background image, I set the background image of the body to red:
var can = document.getElementById('canvasId');
var ctx = can.getContext('2d');
ctx.fillRect(50,50,500,500); // something in the background
var img = new Image();
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
img.src = "https://i.stack.imgur.com/RPEQQ.png"; //transparent png
body {
background-color: red;
}
<canvas id="canvasId"></canvas>

The image that you are trying to display isn't transparent, it simply just has a transparent checkered background.
A link to an image which does have a transparent background can be found here
Using this link fixes your issue:
var can = document.getElementById('canvasId');
var ctx = can.getContext('2d');
ctx.fillRect(50, 50, 500, 500); // something in the background
var img = new Image();
img.src = "https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon#2.png?v=73d79a89bded"; //transparent png
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
canvas {
border: 1px solid black;
}
<canvas id="canvasId" height="300" width="500"></canvas>

Related

Layering an image on top of an HTML canvas that already has an image as its background

I created a canvas element with a colored background, and I came up with the following code to insert an image on top of this canvas:
const canvas = document.getElementById(id);
console.log(canvas);
if (canvas.getContext) {
var context = canvas.getContext('2d');
var img = new Image();
img.src = 'https://google.com/xyz.jpg';
img.onload = function () {
context.save();
context.rect(10, 2, 10, 10);
context.clip();
context.drawImage(img, 0, 0); // image won't resize
context.restore();
};
}
Now this successfully layers the image on top of the canvas (it's cut off however), but I can't find a way to resize the image to be of a certain size (for example 10x10). I tried changing changing the second last line in my code to context.drawImage(img, 0, 0, 10, 10); but this broke my code and the image would not display on the canvas at this point. Any help would be greatly appreciated!
To load and draw an image.
const ctx = can.getContext('2d');
const img = new Image;
img.src = 'https://pbs.twimg.com/media/DyhGubJX0AYjCkn.jpg';
img.addEventListener("load", () => {
// draw image at 10, 10, width and height 50,50
ctx.drawImage(img, 10, 10, 50, 50); // resizes image
}, {once: true});
canvas {
background: green;
}
<canvas id="can" width="200" height = "200"></canvas>

Write text on top of image using canvas

I have a canvas with an image and write it using fillText.
var canvas = document.getElementById("UsedCanvas");
var ctx = canvas.getContext("2d");
var image = new Image();
image.src = img;
image.onload = function() {
ctx.font = "20px Georgia";
ctx.fillText("Hello World!", 10, 50);
}
var dataURL = canvas.toDataURL('image/jpeg', 0.7);
console.log(dataURL);
<canvas id="UsedCanvas"></canvas>
It works perfectly when viewing on canvas, but when I take the url (dataURL) and put it in the browser the text does not appear

Make canvas stretch to fit image

I have a canvas in which I want to render various images, depending on the user. Right now the canvas is fixed size like this:
<canvas width="400" height="300" id={'canvas'}/>
This is how I'm rendering the image:
componentWillReceiveProps(nextProps) {
const ctx = document.getElementById('canvas').getContext('2d');
const img = new Image();
img.onload = function () {
ctx.drawImage(img, 0, 0);
};
img.src = URL.createObjectURL(nextProps.image)
}
But this is what's happening:
So the image at the bottom is too big to be in the canvas, and the other image is too small to fill the image. Also if the image is anything other then a 400x300, it gets cut. How can I prevent it?
In order to get dynamically your canvas dimensions you could have the following componentWillReceiveProps() method:
componentWillReceiveProps(nextProps) {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = function () {
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
};
img.src = URL.createObjectURL(nextProps.image)
}
try by providing the canvas width and height along with ctx.drawImage like:
ctx.drawImage(img, 0, 0, 400, 300);

Convert canvas to base64 error

Result convert is null png image, pls help me
var img = new Image();
img.src = 'http://advs.jp/cp/barcode/code128.cgi?nt=1&height=80&c=Z103B5-190-311378&.png';
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
var dataurl = canvas.toDataURL().replace("data:image/jpeg;base64,", "");
localStorage.setItem("img", dataurl);
$('#bannerImg').attr('src', dataurl);
<img id="bannerImg" src="" alt="Banner Image" width="100%" height="200px" alt="Embbed Image"/>
<canvas id="myCanvas"></canvas>
You have to include everything (drawing to canvas + reading from it + setting this elsewhere) in the onload event of the image. It doesn't work on this snippet (the call to toDataURL) due to a cross-domain issue, but it shall work on your website.
An explanation of why it doesn't work here the call to toDataURL
var imgCanvas = function() {
var img = new Image();
//Wait for image to load before doing something with content
img.onload = function() {
var canvas = document.getElementById("myCanvas");
//Set canvas size to fit the image
canvas.style.height = img.height + 'px';
canvas.style.width = img.width + 'px';
//Draw the image in canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
//Get a dataurl representation of the image where the image itself is in BASE64
var dataurl = canvas.toDataURL();
//Store it in localStorage
localStorage.setItem("img", dataurl);
//Show image from localStorage
//Need jQuery to use this line instead of next one : $('#bannerImg').attr('src', localStorage.getItem("img"));
document.getElementById('bannerImg').setAttribute('src', localStorage.getItem("img"));
};
img.src = 'http://advs.jp/cp/barcode/code128.cgi?nt=1&height=80&c=Z103B5-190-311378&.png';
};
imgCanvas();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Canvas:<br>
<canvas id='myCanvas'></canvas>
<br><br>
Image from dataurl:<br>
<img id='bannerImg'>
Use document.getElementById('bannerImg').setAttribute('src', dataurl); instead.
var showImage = function() {
var img = new Image;
img.onload = function() {
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataurl = canvas.toDataURL();
localStorage.setItem("img", dataurl);
document.getElementById('bannerImg').setAttribute('src', dataurl);
};
img.src = 'http://advs.jp/cp/barcode/code128.cgi?nt=1&height=80&c=Z103B5-190-311378&.png';
};
showImage();
Example: https://jsfiddle.net/atg5m6ym/6152/

Lasso tool in html5 canvas

I'm trying to build a freeform lasso tool to clip an image inside canvas. I'm using fabric.js to draw the shape.
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');
img.onload = function() {
var OwnCanv = new fabric.Canvas('c', {
isDrawingMode: true
});
OwnCanv.freeDrawingBrush.color = "purple"
OwnCanv.freeDrawingBrush.width = 4
ctx.clip();
ctx.drawImage(img, 0, 0);
}
img.src = "http://upload.wikimedia.org/wikipedia/commons/3/33/Jbassette4.jpg?uselang=fi";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>
<canvas id="c" width="500" height="500"></canvas>
This is my attempt which doesn't seem to work, what am I doing wrong here ?
Can anyone help me please? It would really be appreciated.
The image needs to be a fabric.Image.
You could try something like this:
var canvas = document.getElementById('c');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');
img.onload = function() {
var OwnCanv = new fabric.Canvas('c', {
isDrawingMode: true
});
var imgInstance = new fabric.Image(img, {
left: 0,
top: 0,
});
OwnCanv.add(imgInstance);
OwnCanv.freeDrawingBrush.color = "purple"
OwnCanv.freeDrawingBrush.width = 4
OwnCanv.on('path:created', function(options) {
var path = options.path;
OwnCanv.isDrawingMode = false;
OwnCanv.remove(imgInstance);
OwnCanv.remove(path);
OwnCanv.clipTo = function(ctx) {
path.render(ctx);
};
OwnCanv.add(imgInstance);
});
}
img.src = "http://upload.wikimedia.org/wikipedia/commons/3/33/Jbassette4.jpg?uselang=fi";
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>
<canvas id="c" width="500" height="500"></canvas>
See these resources for more:
http://fabricjs.com/fabric-intro-part-1/
Multiple clipping areas on Fabric.js canvas
Fabric.js Clip Canvas (or object group) To Polygon

Categories