【问题标题】:How to center the image inside of canvas in javascript?如何在javascript中将图像居中画布内部?
【发布时间】:2017-07-16 21:59:30
【问题描述】:

在画布内居中图像时遇到问题。画布必须是全尺寸的。整个事情应该创建一个网络预加载器。在这种情况下,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>

【问题讨论】:

  • 设置画布的宽高属性
  • 当我在画布上设置属性的宽度和高度时,图像消失了。

标签: javascript jquery html css canvas


【解决方案1】:

以下仅演示了带有drawImg 的画布内的图像居中。请注意,左边的图像来自 html &lt;img&gt; 元素,而另一个来自 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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-21
    • 2016-11-24
    • 2015-09-23
    • 2020-10-17
    • 2015-09-22
    • 2017-09-24
    • 1970-01-01
    • 2021-01-26
    相关资源
    最近更新 更多