2017-07-16 7 views
0

キャンバスの内側に画像をセンタリングする際に問題があります。キャンバスはフルサイズでなければなりません。全体がWebプリローダーを作成する必要があります。この場合、css内の画像をスタイリングすることはできません。どのようにJavaScriptのキャンバスの内部に画像を中心に?

<style> canvas{ 
    position: fixed; 
    top: 0; 
    left: 0; 
    right: 0; 
    bottom: 0; 
    background-color: #000000; 
    z-index: 99; } 

</style> <body> 
    <canvas id="c"><img id="logo" width="800" height="150" src="imgsource" alt="logo"></canvas> <div> web content </div> 

    <script> 

    jQuery(window).on('load', function() { 
    jQuery('#c').delay(7000).fadeOut('slow'); 
    jQuery('body').delay(7000).css({'overflow':'visible'}); 
    }) 


    window.onload = function() { 
     var c = document.getElementById("c"); 
     var ctx = c.getContext("2d"); 
     var img = document.getElementById("logo"); 
     ctx.drawImage(img, 50, 0); 


    } </script> 
+0

幅と高さ、私は画像が消えキャンバス上の属性の幅と高さを設定していたときキャンバス – Isaac

+0

の属性を設定します。 – Ols

答えて

0

以下は、drawImgというキャンバス内の画像のセンタリングについてのみ示しています。左側の画像はhtml <img>要素のもので、もう1つはdrawImg呼び出しのものです。

描画の前にイメージが読み込まれるのを待つ必要がありますが、すでに.on('load', ...)を使用していることを認識していると思います。

2つの画像が存在しないようにするには、image elementをjavascriptで作成し、ドキュメントに追加せずにレンダリングにのみ使用してください。

let canvas = document.getElementById("canvas"); 
 
let ctx = canvas.getContext("2d"); 
 
let img = document.getElementById("i"); 
 

 
//just to make the area the canvas occupies visible 
 
ctx.fillStyle = 'grey'; 
 
ctx.fillRect(0, 0, canvas.width, canvas.height); 
 

 
//draw the image centered 
 
ctx.drawImage(
 
    img, 
 
    canvas.width/2 - img.width/2, 
 
    canvas.height/2 - img.height/2 
 
);
<html> 
 
    <body> 
 
    <img id="i" src="http://i.imgur.com/kdJicdy.png"/> 
 
    <canvas id="canvas" width="320" height="240">Your browser doesn't support canvas</canvas> 
 
    </body> 
 
</html>

関連する問題