Below is part of a web drawing app using HTML5 Canvas.
My next step is to allow contents from local files to be selected and rendered onto the canvas. The files can be txt or common image formats like png.
In the code, the file is selected then if the extension is txt the contents are treated as text, and if the extension is png the image data should be read and rendered on the canvas.
However, with the png file, I get the error:
Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D':
The provided value is not of type '(CSSImageValue or HTMLCanvasElement or
HTMLImageElement or HTMLVideoElement or ImageBitmap or OffscreenCanvas or
SVGImageElement or VideoFrame)'.
Here is the code:
<script>
function addTxtFileContent(e) {
console.log('addTxtFileContent');
var fc = e.target.result;
console.log('addFileContent: ' + fc);
var fsize = document.getElementById("TextFontSize").value;
var font = "";
if ( textitalic ) font += 'italic ';
if ( textbold ) font += 'bold ';
font += fsize + 'px ' +
document.getElementById("TextFontList").value;
console.log('addFileContent font: ' + font );
context.font = font;
context.fillStyle = scolor;
context.textAlign = textalign;
context.fillText(fc, 400, 200);
}
function addImgFileContent(e, img) {
console.log('addImgFileContent');
context.drawImage(img, 100, 100);
}
function readFile(e) {
console.log('readFile');
var file = e.target.files[0];
if (!file) return;
var reader = new FileReader();
var ext = String(file.name).split('.').pop();
console.log('readFile name: ' + file.name + ' ext:' + ext);
switch ( ext )
{
case 'txt':
reader.onload = function(e) {
addTxtFileContent(e);
}
reader.readAsText(file);
break;
case 'png':
reader.readAsDataURL(file);
reader.onload = function (e) {
var image=new Image();
image.src=e.target.result;
image.onload = function () {
addImgFileContent(image); // <<< Error reported here
};
}
}
}
</script>