I have a canvas. Now i want to make an image of the canvas. This function i already developed. I've got an image with the right src-attribute. But if i want to append this image-element to the html-container, it doesn't works. Nothing happens.
I don't know why. The html-container is available, the image is correct.
Here is some code:
Function to create the picture
function createPicture(canvas, container){
let dataURL = canvas.toDataURL({
width: canvas.width,
height: canvas.height,
left: 0,
top: 0,
format: 'jpeg',
});
let image = new Image();
image.setAttribute("src", dataURL);
container.append(image);
}
Calling this function
createPicture(canvas, $("#test"));
Image in the console:
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…">
CodePudding user response:
Your code works fine for me, see my sample below
function createPicture(canvas, container){
let dataURL = canvas.toDataURL({
width: canvas.width,
height: canvas.height,
left: 0, top: 0,
format: 'jpeg',
});
let image = new Image();
image.setAttribute("src", dataURL);
container.append(image);
}
let co = document.getElementById("container")
let ca = document.getElementById("canvas")
var ctx = ca.getContext("2d");
ctx.rect(10, 10, 80, 60);
ctx.arc(50, 50, 30, 0, 4);
ctx.stroke();
createPicture(ca, co)
canvas {
border: 3px solid blue;
}
div {
border-color: red;
border-style: solid;
width: 100px;
height: 100px;
}
<canvas id="canvas" width=100 height=100></canvas>
<div id="container"></div>
Only thing I could think of is you are doing something on your canvas after you call the createPicture an expecting it to be there, if you still run into problems I would recommend you to create a code snippet reproducing your problem and post it here
Check on your dev console, make sure you see the image element:
If you don't see it then the problem must be the container