2016-09-15 2 views
0

ウェブベースのゲームに問題があります。実際のウィンドウを再スケーリングしている間でも、ドキュメントウィンドウと同じディメンションを持つはずのキャンバスに、データURLにエンコードしたSVGを描画しようとします。SVGファイルを動的な次元のHTMLキャンバス要素に追加するにはどうすればよいですか?

(function() { 
 
\t var canvas = document.getElementById('canvas'), 
 
\t \t context = canvas.getContext('2d'); 
 

 
\t // resize the canvas to fill browser window dynamically 
 
\t window.addEventListener('resize', resizeCanvas, false); 
 

 
\t function resizeCanvas() { 
 
\t \t canvas.width = window.innerWidth; 
 
\t \t canvas.height = window.innerHeight; 
 

 
\t \t /** 
 
\t \t * Your drawings need to be inside this function otherwise they will be reset when 
 
\t \t * you resize the browser window and the canvas goes will be cleared. 
 
\t \t */ 
 

 
\t \t drawSVGBackground(); 
 
\t } 
 
\t resizeCanvas(); 
 

 
\t function drawSVGBackground() { 
 
\t \t var img = new Image(); 
 
\t \t img.onload = function() { 
 
\t \t \t ctx.drawImage(img, 0, 0); 
 
\t \t }; 
 
\t \t img.src = "data:image/svg+xml;base64,(A really long encryption that took up a lot of space)"; 
 
\t } 
 
})();
* { 
 
\t margin: 0; 
 
\t padding: 0; 
 
} 
 

 

 
/* to remove the top and left whitespace */ 
 

 
html, 
 
body { 
 
\t width: 100%; 
 
\t height: 100%; 
 
} 
 

 

 
/* just to be sure these are full screen*/ 
 

 
canvas { 
 
\t display: block; 
 
} 
 

 

 
/* To remove the scrollbars */
<canvas id="canvas"></canvas>

私は、Base64エンコーディングを使用して、この目的のために非常に良いアイデアだったかはわからない、と私はまた、間違っているかわからないんだけど。

+0

追記:私がチェックした最後の時間を、Firefoxはキャンバスに適切にSVGを拡張しませんでした。おそらく、これは修正されたので、複数のブラウザでテストするようにしてください。 –

+0

@JacqueGoupil、widthとheight属性は絶対的な長さ(つまり%ではない)に設定する必要があります.FFFはそれをまったく描画しません。実際はクロムだけが推測しようとします。それ以外の場合は、 'drawImage()'と一緒に使用したときに、FFが正しくsvgを拡大していないことはありませんでした。 – Kaiido

答えて

1

まず、SVG's can be data url encoded。第二に

Learn how to debug JavaScript

は第三に、私は固定/ JavaScriptのリファクタリング:

(function() { 
    var canvas = document.getElementById('canvas'), 
     context = canvas.getContext('2d'), 
     img = new Image(); 

    // resize the canvas to fill browser window dynamically 
    window.addEventListener('resize', resizeCanvas, false); 

    function resizeCanvas() { 
     canvas.width = window.innerWidth; 
     canvas.height = window.innerHeight; 

     /** 
     * Your drawings need to be inside this function otherwise they will be reset when 
     * you resize the browser window and the canvas goes will be cleared. 
     */ 

     drawSVGBackground(); 
    } 
    resizeCanvas(); 

    function drawSVGBackground() { 
     context.drawImage(img, 0, 0, canvas.width, canvas.height); 
    } 


    img.onload = function() { 
     drawSVGBackground(); 
    }; 
    img.src = "data:image/svg+xml;base64,(A really long encryption that took up a lot of space)"; 
})(); 
+0

ありがとう、 –

関連する問題