我有以下代码用于生成html画布:
<canvas id="glCanvas" class="canvases" width="20" height="20"></canvas>
并设置颜色我有以下内容:
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
是否有一种在运行时动态添加和删除边框的简单方法?也就是说,当满足特定的if语句条件时,在画布周围绘制一个红色边框,当不再满足时,将删除边框。可以使用CSS / Javascript / WebGL完成吗?
谢谢
答案 0 :(得分:1)
您的问题与WebGL或画布无关。您可以使用类似
的内容在任何元素上设置边框 someElement.style.border = "10px solid red";
用
删除边框 someElement.style.border = "none";
对于画布我建议你将画布包裹在像这样的div中
<div id="border"><canvas id="glCanvas"></canvas></div>
然后查找div
borderDiv = document.querySelector("#border");
并且基于任何条件使用顶部的代码;
const borderDiv = document.querySelector("#border");
const showButton = document.querySelector("#show");
const hideButton = document.querySelector("#hide");
showButton.addEventListener('click', function() {
borderDiv.style.border = "10px solid red";
});
hideButton.addEventListener('click', function() {
borderDiv.style.border = "none";
});
// draw something in canvas.
const gl = document.querySelector("#glCanvas").getContext("webgl");
gl.clearColor(0,0,1,1);
gl.clear(gl.COLOR_BUFFER_BIT);
#border { display: inline-block; }
#glCanvas { width: 100%; height: 100%; display: block; }
<div id="border"><canvas id="glCanvas"></canvas></div>
<div>
<button id="show">show border</button>
<button id="hide">hide border</button>
</div>
你也可以添加和删除样式
someElement.className = "styleWithBorder";
someElement.className = "styleWithoutBorder";
您可以通过用空格分隔来应用多个类
someElement.className = "style1 style2";
const borderDiv = document.querySelector("#border");
const showButton = document.querySelector("#show");
const hideButton = document.querySelector("#hide");
showButton.addEventListener('click', function() {
borderDiv.className = "styleWithBorder";
});
hideButton.addEventListener('click', function() {
borderDiv.className = "";
});
// draw something in canvas.
const gl = document.querySelector("#glCanvas").getContext("webgl");
gl.clearColor(0,0,1,1);
gl.clear(gl.COLOR_BUFFER_BIT);
/* these 2 lines make the border go inside the element
instead of outside IF the element has a defined width and height */
html { box-sizing: border-box; height: 100%; }
*, *:before, *:after { box-sizing: inherit; }
/* this setting removes the default 5px margin on the body
and makes the body fill the window so our div will match */
body { margin: 0; height: 100%; }
/* this line makes our border fill the body. We need to set
the size so the border will go inside */
#border { width: 100%; height: 100%; }
/* this line makes the canvas fill the div it's inside
and display:block makes it not add whitespace at the end */
#glCanvas { width: 100%; height: 100%; display: block; }
/* here's our border */
.styleWithBorder { border: 10px solid yellow; }
/* make the ui show up over the rest */
#ui { position: absolute; left: 1em; top: 1em; }
<div id="border"><canvas id="glCanvas"></canvas></div>
<div id="ui">
<button id="show">show border</button>
<button id="hide">hide border</button>
</div>