Canvas To Base64 On Image Src
I want to convert the rawImg to base64 and pass it on image.src. I will be needing the base64 dataURL to put effects on my canvas. Pls see my code below: function onLoad() { ca
Solution 1:
Use
HTMLCanvasElement.toDataURL()
, returns a dataURI
containing a representation of the image in the format specified by the type parameter(The default type isimage/png
)
functiononLoad() {
canvas = document.querySelector("#myCanvas");
context = canvas.getContext("2d");
var image = newImage();
image.onload = function() {
if (image.width != canvas.width)
canvas.width = image.width;
if (image.height != canvas.height)
canvas.height = image.height;
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(image, 0, 0, canvas.width, canvas.height);
filterCanvas(imageFilter);
var imageURL = canvas.toDataURL();
YOUR_IMAGE.src = imageURL; //Select `YOUR_IMAGE` using getElementById/querySelector/...
}
image.src = "flower.jpg";
}
Solution 2:
With HTML snippets as:
<canvasid="myCanvas"></canvas><span>Resultant data URL: </span><spanid="result"></span>
And, updating your javascript code as below:
canvas = document.querySelector("#myCanvas");
context = canvas.getContext("2d");
var image = newImage();
image.onload = function() {
if (image.width != canvas.width)
canvas.width = image.width;
if (image.height != canvas.height)
canvas.height = image.height;
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(image, 0, 0, canvas.width, canvas.height);
// filterCanvas(imageFilter);var imageURL = canvas.toDataURL();
alert(imageURL);
document.querySelector("#result").innerHTML = imageURL;
}
image.src = "flower.jpg";
You will get the resultant base64 string within the #result
span element. Please try this.
Post a Comment for "Canvas To Base64 On Image Src"