I am trying to load an image from a file and draw it on a canvas. I have this..
const canvas = document.createElement("canvas");
const context = canvas.getContext("2d");
myImage = new Image();
myImage.src = "img/image.jpg";
context.drawImage(myImage, 0, 0, 100, 100);
This is not drawing anything on the screen, where am I going wrong? I can see the image being loaded by developer tools so I know that it can find the file itself.
If the canvas element is already on the page, you'll need to replace the createElement method with querySelector:
// const canvas = document.createElement("canvas");
const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d");
myImage = new Image();
myImage.src = "img/image.jpg";
myImage.addEventListener("load", ()=>{
context.drawImage(myImage, 0, 0, 100, 100);
}); // Thanks to Xion 14 for the reminder!
Otherwise, you'll need to append the canvas element to the DOM, e.g. via document.body.appendChild( canvas );
Related
If I have an image in base64 ex.
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABDAAwfqNRk/rjcYX+PxrV/wtWqwJSTlboMgAAAABJRU5ErkJggg==
What's the fastest way to change a filter (ex. brightness, contrast) programmatically and without creating any img or canvas tag in the view? Then once changed, convert it back to a base64 url?
You can do this by putting the image onto a HTML canvas with filters applied, then turning that canvas back into a base64 URL.
Since you never add the canvas to the document, it will never be seen.
This is how you would do it asynchronously:
This takes about 1-10ms
function applyFiltersToImage(imageURL, callBack) {
// load the image url into an image object
const image = new Image();
image.src = imageURL;
const canvas = document.createElement("canvas");
const ctx = canvas.getContext('2d');
image.onload = () => {
canvas.width = image.width;
canvas.height = image.height;
// apply css filters here
ctx.filter = 'brightness(0.5) contrast(2)';
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
// turn canvas back into a base64 image URL
callBack(canvas.toDataURL("image/png"));
}
}
You could do it synchronously if you already have the Image instance loaded.
This is how you will do it synchronously:
function applyFiltersToImageSync(imageObject) {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext('2d');
canvas.width = imageObject.width;
canvas.height = imageObject.height;
// apply css filters here
ctx.filter = 'brightness(0.5) contrast(2)';
ctx.drawImage(imageObject, 0, 0, canvas.width, canvas.height);
//turn canvas back into a base64 image
return canvas.toDataURL("image/png");
}
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);
I'm trying to have a page where users can customize a canvas and then email the finished project to themselves. I set the background of the canvas using the following javascript:
function setbackground1() {
document.getElementById('myCanvas').setAttribute("class",
"background1");
}
function setbackground2() {
document.getElementById('myCanvas').setAttribute("class",
"background2");
}
and included a form on the page to populate the rest of the canvas. I have tried various ways of including canvas.toDataURL() in order to save the canvas as an image that can later be emailed to them however the background image is not part of the saved image. (similar problem to Canvas to Save Image and Email but my text saves not my images)
I've been trying variations of this but it's not working for me.
function setbackground11() {
var img = new Image();
img.src = 'background1.jpg';
img.onload = function () {
ctx.fillRect( 0, 0, canvas.width, canvas.height )
}
}
I believe that I somehow have to reference myCanvas id as well
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');`
CSS styles aren't part of the canvas image. For a solid color:
ctx.fillStyle = 'green'
ctx.fillRect( 0, 0, canvas.width, canvas.height )
For an image:
var img = new Image();
img.src = 'background1.jpg';
img.onload = function () {
ctx.drawImage( img, 0, 0, canvas.width, canvas.height )
// do the rest of your drawing over the background
}
I am trying to add an image to my pdf:
var image = '../images/example.jpg';
doc.addImage(image, 'JPEG', 0, 0, 700, 145);
and I get this error:
Error: Supplied data is not a JPEG
however, when I add a base64 image:
var image = 'data:image/jpeg;base64,/9j/6GADS...'
doc.addImage(image, 'JPEG', 0, 0, 700, 145);
it works fine!
why is the first version not working?
I am trying this:
var image = $base64.encode('../images/example.jpg')
the same error above again!
what is happening here? what is the solution?
You can use this.
function toDataUrl(src, callback, outputFormat) {
// Create an Image object
var img = new Image();
// Add CORS approval to prevent a tainted canvas
img.crossOrigin = 'Anonymous';
img.onload = function() {
// Create an html canvas element
var canvas = document.createElement('CANVAS');
// Create a 2d context
var ctx = canvas.getContext('2d');
var dataURL;
// Resize the canavas to the image dimensions
canvas.height = this.height;
canvas.width = this.width;
// Draw the image to a canvas
ctx.drawImage(this, 0, 0);
// Convert the canvas to a data url
dataURL = canvas.toDataURL(outputFormat);
// Return the data url via callback
callback(dataURL);
// Mark the canvas to be ready for garbage
// collection
canvas = null;
};
// Load the image
img.src = src;
}
I'm trying to crop a image using ctx.drawImage() and get the cropped image data using canvas.toDataURL(). However I can't get the right data until I refresh the page few times. I want to know how can I get the cropped image data immediately instead of refresh the page.
<script>
var imageObj = new Image();
imageObj.src = 'http://localhost:63342/war/img/IMG_20140131_102234.jpg';
var canvas = document.createElement('canvas');
canvas.width = 30;
canvas.height = 30;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
ctx.drawImage(imageObj, 0, 0, 715, 715, 0, 0, 30, 30);
// Get the data-URL formatted image
var dataURL = canvas.toDataURL("image/png");
console.log(dataURL);
</script>
When I first open the page the data I got are :
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAAPklEQVRIS+3TsQ0AMAgEMdh/afr0D0XMACBZR9fR9NHdcnhNHjXqmIC4YrTvYtSoYwLiitH6Y3GJKybwX1wD6fcAH1bniBkAAAAASUVORK5CYII=
These data are much smaller than the data I got after I refresh the page few times. I'm really confused why this happened and how to fix the problem.
You need to wait for your image to be loaded. Use the onload event.
The reason it works after a few times is because the browser caches it, and makes it load before you run your toDataURL code.
For example, your code would look like this:
var imageObj = new Image();
imageObj.src = 'http://localhost:63342/war/img/IMG_20140131_102234.jpg';
var canvas = document.createElement('canvas');
canvas.width = 30;
canvas.height = 30;
// Copy the image contents to the canvas
var ctx = canvas.getContext("2d");
imageObj.addEventListener('load', function () {
ctx.drawImage(imageObj, 0, 0, 715, 715, 0, 0, 30, 30);
// Get the data-URL formatted image
var dataURL = canvas.toDataURL("image/png");
console.log(dataURL);
});