Reputation: 177
I am using react konva to draw images on a canvas. I have two different Layers (canvas in konva) inside a Stage Element. One picture is predetermined and one gets updated by an input at runtime. Both Pictures get shown fine, but when I try to save them, the one coming from the input is just a black png and not the picture I selected.
Javascript:
imageUpload when input is clicked.
const handleImageUpload = e => {
setSelected(false);
let canvas = backgroundCanvas.current;
let ctx = canvas.getContext('2d');
newImage.onload = function() {
newImage.crossOrigin = 'Anonymus';
ctx.drawImage(newImage, 0, 0);
};
const [file] = e.target.files;
if (file) {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = e => {
ctx.clearRect(0, 0, canvas.canvas.width, canvas.canvas.height);
newImage.src = e.target.result;
};
}
};
It shows the image on the screen like i want to and looks like it works, however, if I want to save the canvas as a png file, it is not there anymore.
Save function:
const saveImage = () => {
let backgroundCanvasSave = backgroundCanvas.current;
const backgroundCanvasData = backgroundCanvasSave.toDataURL({
mimeType: 'image/png',
});
downloadURI(backgroundCanvasData, 'stage.png');
};
JSX:
<div>
<Stage
ref={canvasStage}
width={window.innerWidth}
height={window.innerHeight}
>
<Layer
ref={backgroundCanvas}
onClick={() => {
setSelected(false);
}}
onTap={() => {
setSelected(false);
}}
/>
<Layer ref={lampCanvas}>
<Lamp
shapeProps={shape}
isSelected={selected}
onSelect={() => {
setSelected(true);
}}
onChange={setShape}
/>
</Layer>
</Stage>
<label
for="files"
class="btn"
style={{
border: '1px solid',
display: 'inline block',
padding: '6px 12px',
cursor: 'pointer',
}}
>
Bild hochladen
<input
id="files"
visibility="hidden"
type="file"
accept="image/*"
style={{ display: 'none' }}
onChange={handleImageUpload}
ref={imageUploader}
/>
</label>
<label
class="btn"
style={{
border: '1px solid',
display: 'inline block',
padding: '6px 12px',
cursor: 'pointer',
}}
onClick={saveImage}
>
Bild speichern
</label>
</div>
);
The goal of the application would be to save the Stage with both pictures inside it, but as I said, the background is always black, while the lamp is showing.
Thanks in advance!
Upvotes: 1
Views: 2367
Reputation: 20288
Do not use the context
of a layer directly. Konva may lose your changes while exporting the canvas.
To fix the issue just draw your input as <Image />
component:
const newImage = new Image();
newImage.onload = () => {
this.setState({ image: newImage })
};
newImage.crossOrigin = 'Anonymus';
newImage.src = e.target.result;
// in render:
<Layer
ref={backgroundCanvas}
onClick={() => {
setSelected(false);
}}
onTap={() => {
setSelected(false);
}}
>
<Image image={this.state.image} />
</Layer>
Upvotes: 2