2017-07-16 101 views
0

我在畫布內部定位圖像時遇到問題。帆布必須全尺寸。整個事情應該創建一個網頁預加載器。在這種情況下,在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

上height屬性當我設置屬性的寬度和高度的圖像消失在畫布上。 – Ols

回答

0

以下僅說明了一個圖像與drawImg畫布內的定心。請注意,左側的圖像來自html <img>元素,而另一個來自drawImg呼叫。

在stackoverflow之外,您必須等待圖像加載之前加載它,但是因爲您也已經使用.on('load', ...)我假設您知道這一點。

爲避免產生兩個圖像,請在javascript中創建image element,並且不要將其添加到文檔中,而只能將其用於渲染。

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>