こんにちは。いつもありがとうございます。HTML5 Canvasで数枚の画像を読み込み表示した時に予期せぬ挙動になるため質問させてください。
##毎回順序がバラバラにレンダーされる
数枚のサイズの違う画像を重ねて表示することで、奥行きのついたシーンを作ろうとしているのですが、リロードするたびにその順序がバラバラです。
多分画像の読み込みが終わった順に表示されているような気もするのですが、それをどうやって解決すればいいのか分からず。。。
現在使っている画像は全て同じなのですが、後にそれぞれの画像を別のものに変更する予定です。
####コード
JavaScript
1 2var treeArray = []; 3 4window.onload = function () { 5 ctx = document.getElementById('canvas').getContext('2d'); 6 7 for(var i = 0; i < 10; i++){ 8 treeArray.push(new Tree("../assets/images/tree.png",i/2)) 9 } 10 for(var i = 0; i < treeArray.length; i++){ 11 // ctx.globalCompositeOperation='destination-over'; 12 treeArray[i].draw(); 13 } 14 15}//Close window event listener 16 17function Tree(imgURL,zoomLevel){ 18 this.img = new Image(); 19 this.img.onload; 20 this.zoomLevel = zoomLevel 21 this.img.naturalWidth; 22 this.img.naturalHeight; 23 this.img.scaleMultiplier; 24 this.img.width; 25 this.img.height; 26 this.imgFullScreenH 27 this.img.src = imgURL; 28} 29 30Tree.prototype.draw = function(){ 31 this.img.addEventListener("load", function(){ 32 33 this.img.zoomScaleMultiplier = (this.zoomLevel * 0.9) 34 this.img.scaleMultiplier = (window.innerHeight / this.img.naturalHeight); 35 // this.img.height = window.innerHeight * (-this.zoomLevel); 36 // this.img.width = this.img.naturalWidth*this.img.scaleMultiplier * (-this.zoomLevel); 37 this.img.height = window.innerHeight * this.img.zoomScaleMultiplier; 38 this.img.width = this.img.naturalWidth * this.img.scaleMultiplier * this.img.zoomScaleMultiplier; 39 this.translate = { 40 x : (this.img.width - window.innerWidth)/2, 41 y : (this.img.height - window.innerHeight)/1.2, 42 } 43 44 console.group("sizes") 45 console.log("this.img.scaleMultiplier",this.img.scaleMultiplier) 46 console.log("this.img.width",this.img.width) 47 console.log("this.img.height",this.img.height) 48 console.log("this.img.naturalWidth",this.img.naturalWidth) 49 console.log("this.img.naturalHeight",this.img.naturalHeight) 50 console.log("this.img.onload",this.img.onload) 51 console.groupEnd() 52 53 ctx.drawImage(this.img,-this.translate.x, -this.translate.y,this.img.width, this.img.height); 54 55 }.bind(this),false) 56 57/* 58 59To get width and height of images, you need to write those codes into image Event Listener. 60 61-------------------------------------------------------------------------------------------- 62"How can I control z-index of canvas objects?" 63http://stackoverflow.com/questions/14250697/how-can-i-control-z-index-of-canvas-objects 64-------------------------------------------------------------------------------------------- 65 66 67*/ 68 69} 70 71function reset() { 72 location.reload(); 73}
どなたか原因と解決方法をご存じないでしょうか??よろしくお願いします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。