こんにちは。いつもありがとうございます。最近Canvasを使う機会がありまして勉強中です。
##エラーが出ます
Canvas に画像をオブジェクトとして表示しようと、下のコード実行すると、
JavaScript
1window.onload = function () { 2 var treeArray = []; 3 4 ctx = document.getElementById('canvas').getContext('2d'); 5 for(var i = 0; i < 5; i++){ 6 treeArray.push(new Tree("../assets/images/tree.png",i*100,i*100)) 7 treeArray[i].draw(); 8 } 9}//Close window event listener 10 11function Tree(imgURL,imgWidth,imgHeight){ 12 this.img = new Image; 13 this.img.width = imgWidth; 14 this.img.height = imgHeight; 15 this.img.src = imgURL; 16 this.translate = { 17 x : (window.innerWidth - this.img.width)/2, 18 y : (window.innerHeight - this.img.height)/2 19 } 20} 21 22Tree.prototype.draw = function(){ 23 this.img.addEventListener("load", function(){ 24 ctx.drawImage(this.img,0, 0); 25 }, false) 26} 27 28function reset() { 29 location.reload(); 30}
Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)' at HTMLImageElement.<anonymous>
このエラーが出ます。
しかし、オブジェクトとして表示しなければ普通に表示されます。何が間違っていますか??わかる方おられましたら教えてください。お願いします。
###追記
オブジェクトとして表示しなかった場合のコードです。
JavaScript
1var imgTest; 2 3 4window.onload = function () { 5 var treeArray = []; 6 imgTest = new Image; 7 imgTest.src = "../assets/images/test.png" 8 ctx = document.getElementById('canvas').getContext('2d'); 9 imgTest.onload = function(){ 10 ctx.drawImage(imgTest, 0, 0); 11 } 12} 13}
回答2件
あなたの回答
tips
プレビュー