如何在html中的图像的顶部设置画布 [英] How to set canvas on top of image in html

查看:279
本文介绍了如何在html中的图像的顶部设置画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个包含画布的index.html:

Say I have a index.html with a canvas in it:

<html>
<head>
</head>
<body style="text-align: center;background: #f2f6f8;">

<div style="display:inline-block;width:auto; margin: 0 auto; background: black; position:relative; border:5px solid black; border-radius: 10px; box-shadow: 0 5px 50px #333">
    <canvas id="gameCanvas" width="320" height="480"></canvas>
</div>
</body>
</html>

并且画布以这种方式显示正确~~~

and the canvas is showing ok this way ~~~

现在我想把一个图像作为背景放在画布上,我试图在正文中添加一个img标签:

Now I want to put a image as background behind the canvas and I tried to add a img tag in the body:

<html>
<head>
</head>
<body style="text-align: center;background: #f2f6f8;">
<img src="xxx.png" alt="" />
<div style="display:inline-block;width:auto; margin: 0 auto; background: black; position:relative; border:5px solid black; border-radius: 10px; box-shadow: 0 5px 50px #333">
    <canvas id="gameCanvas" width="320" height="480"></canvas>
</div>
</body>
</html>

但是画布似乎显示在图像不在其顶部...

but then the canvas appeared to show after the image not on top of it ...

我真的对html一无所知,我认为这不应该是那么难以完成,希望有人可以在这里给一个手,谢谢:)

I really know nothing about html I think it should not be that hard to get this done, hope someone can give a hand here, thanks :)

推荐答案

即时演示

Live Demo

您只需使用 z-index 。我把图像和canvas元素放在一个容器中,并将它们放在这样的位置,使画布总是在图像上。

You just need to use z-index. I put the image and the canvas element in a container, and position them so the canvas will always be over the image.

另一个注意事项,你不应该canvas使用CSS,你应该总是通过属性直接。在我的小提琴,我是通过JS。

Also another note, you shouldn't size your canvas using CSS, you should always do it via the properties directly. In my fiddle I did it via JS.

<div id="container">
    <img class='img' src="http://lorempixel.com/320/480/" alt="" />
    <canvas id="gameCanvas" width="320" height="480"></canvas>
</div>



CSS



CSS

body{text-align: center;background: #f2f6f8;}
.img{position:absolute;z-index:1;}

#container{
    display:inline-block;
    width:320px; 
    height:480px;
    margin: 0 auto; 
    background: black; 
    position:relative; 
    border:5px solid black; 
    border-radius: 10px; 
    box-shadow: 0 5px 50px #333}

#gameCanvas{
    position:relative;
    z-index:20;
}

这篇关于如何在html中的图像的顶部设置画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆