[英]How to center the image inside of canvas in javascript?
我在畫布內居中圖像時遇到問題。 畫布必須是全尺寸的。 整個事情應該創建一個網絡預加載器。 在這種情況下,css 內的樣式圖像不起作用。
<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>
以下僅演示了使用drawImg
在畫布內居中的圖像。 請注意,左邊的圖像來自 html <img>
元素,而另一個來自drawImg
調用。
在 stackoverflow 之外,您必須等待圖像加載后再繪制,但由於您也已經使用.on('load', ...)
我假設您已經意識到這一點。
為避免有兩個圖像,請在 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>
var canvas = document.getElementById('canvas');
var image = new Image();
image.src = 'http://placehold.it/300x550';
image.onload = function () {
var canvasContext = canvas.getContext('2d');
var wrh = image.width / image.height;
var newWidth = canvas.width;
var newHeight = newWidth / wrh;
if (newHeight > canvas.height) {
newHeight = canvas.height;
newWidth = newHeight * wrh;
}
var xOffset = newWidth < canvas.width ? ((canvas.width - newWidth) / 2) : 0;
var yOffset = newHeight < canvas.height ? ((canvas.height - newHeight) / 2) : 0;
canvasContext.drawImage(image, xOffset, yOffset, newWidth, newHeight);
};
<canvas id="canvas" width="500" height="500" style="border: 1px solid black" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.