我在使用 canvas 代码时遇到了很大的问题,我在页面(在 Logo 中)中只使用了 1 次,但工作正常,而且我试图将它用作菜单按钮,这就是问题所在,我真的不知道我做错了什么,希望你们中的一些人帮助我。
这是我用于 Logo 的代码并且工作正常:
HTML 代码:
<html>
<head>
<title>canvas</title>
</head>
<body>
<div id="container">
<div id="logo">
<canvas style="" width="800" id="broken-glass"></canvas>
<h1 style="color: rgba(250, 250, 250, 0.95);" id="logo-title">Canvas</h1>
</div>
<script type="text/javascript">
(function() {
var isCanvasSupported = function () {
var elem = document.createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
};
if( isCanvasSupported() ) {
var canvas = document.getElementById('broken-glass'),
context = canvas.getContext('2d'),
width = canvas.width = Math.min(800, window.innerWidth),
height = canvas.height,
numTriangles = 100,
rand = function(min, max){
return Math.floor( (Math.random() * (max - min + 1) ) + min);
};
window.drawTriangles = function(){
context.clearRect(0, 0, width, height);
var hue = rand(0,360);
var increment = 80 / numTriangles;
for(var i = 0; i < numTriangles; i++) {
context.beginPath();
context.moveTo(rand(0,width), rand(0,height) );
context.lineTo(rand(0,width), rand(0,height) );
context.lineTo(rand(0,width), rand(0,height) );
context.globalAlpha = 0.5;
context.fillStyle = 'hsl('+Math.round(hue)+', '+rand(15,60)+'%, '+ rand(10, 60) +'%)';
context.closePath();
context.fill();
hue+=increment;
if(hue > 360) hue = 0;
}
canvas.style.cssText = '-webkit-filter: contrast(115%);';
};
document.getElementById('logo-title').style.color = 'rgba(250, 250, 250, 0.95)';
drawTriangles();
var el = document.getElementById('logo');
el.onclick = function() {
drawTriangles();
};
}
})();
</script>
</div>
</body>
</html>
这是 CSS 代码:
#broken-glass
{
position: absolute;
left: 0px;
top: 0px;
width: 100%;
}
#logo h1
{
text-align: center;
font-weight: 700;
width: 100%;
color: #000;
position: absolute;
left: 0px;
-moz-user-select: none;
cursor: pointer;
margin-top: 27px;
font-size: 63px;
line-height: 1.4;
top: 0px;
margin-bottom: 5px;
text-rendering: optimizelegibility;
font-family: Calibri,"PT Sans","Trebuchet MS","Helvetica Neue",Arial;
}
当我将 id 的 (#) 更改为类 (.) 并将 html 中的“id”标签更改为“class”标签时,出现了大问题, Canvas 重叠了...... h1 标签的文本不在 Canvas 中...只是问题的 hell ,有人能告诉我我做错了什么吗?如何解决它,我在几个小时内都在尝试...
提前致谢!
最佳答案
您可以尝试在您的 css 中的每个代码中放置一个 !important。 示例:
text-align: center !important;
font-weight: 700 !important;
这解决了我之前的问题,希望它也能解决你的问题。
关于javascript - 多个 Canvas 作为带有 onclick 事件的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25354927/