I'm trying to save a canvas with images to PNG, but when I try this:
var myCanvas = document.getElementById("myCanvas");
var img = document.createElement('img');
var ctx = myCanvas.getContext ? myCanvas.getContext('2d') : null;
img.src = 'image.png';
img.onload = function () {
ctx.drawImage(img, 0, 0, myCanvas.width, myCanvas.height);
}
var data = myCanvas.toDataURL("image/png");
if (!window.open(data)) {
document.location.href = data;
}
I only get a blank transparent image without the image. What am I doing wrong?
Saving HTML canvas as an image is pretty easy, it can be done by just right-clicking on the canvas and save it as an image.
function convertCanvasToImage() { let canvas = document. getElementById("canvas"); let image = new Image(); image. src = canvas. toDataURL(); return image; } let pnGImage = convertCanvasToImage(); document.
Open your HTML file in your browser or any viewable tool. Take a snapshot of an area with your screen capture tool (Snipping tool on Windows, for example). Click File > Save as. Select the location and select the Save as type as JPG.
You need to put the window.open
call in the load handler since this happens asynchronously.
img.onload = function () {
ctx.drawImage(img, 0, 0, myCanvas.width, myCanvas.height);
var data = myCanvas.toDataURL("image/png");
if (!window.open(data)) {
document.location.href = data;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With