我想为我的HTML CANVAS添加一个边框,并认为以下代码可以做到这一点.
问题:如何在代码和HTML代码中围绕Canvas设置边框>
码:
context.fillStyle = 'red';
context.strokeStyle = 'black';
Run Code Online (Sandbox Code Playgroud)
以下代码是整个HTML文件.它并不是那么大,所以我只是粘贴了它.
码:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chapter 4 Example 1: Image Basics</title>
<script src="modernizr.js"></script>
<script type="text/javascript">
window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded() {
canvasApp();
}
function canvasSupport () {
return Modernizr.canvas;
}
function canvasApp(){
if (!canvasSupport()) {
return;
}else{
var theCanvas = document.getElementById('canvas');
var context = theCanvas.getContext('2d');
context.fillStyle = 'red';
context.strokeStyle = 'black';
context.font = '20pt Verdana';
context.fillText('Some text', 50, 50);
context.strokeText('Some text', 50, 50);
context.fill();
context.stroke();
}
var spaceShip=new Image();
spaceShip.src="ship1.png";
spaceShip.addEventListener('load', eventShipLoaded , false);
function eventShipLoaded() {
drawScreen();
}
function drawScreen() {
context.drawImage(spaceShip, 10, 10);
context.drawImage(spaceShip, 50, 50);
context.drawImage(spaceShip, 150, 50);
}
}
</script>
</head>
<body>
<div style="position: absolute; top: 50px; left: 50px;">
<canvas id="canvas" width="500" height="500">
Your browser does not support the HTML 5 Canvas.
</canvas>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
bro*_*njc 13
你可以使用CSS.这是一个例子.http://jsfiddle.net/amER5/1/
#canvas {
height: 100px;
width: 100px;
border: 1px solid blue;
}
Run Code Online (Sandbox Code Playgroud)
或内联:
<canvas id="canvas" width="500" height="500" style="border: 1px solid black;">
Your browser does not support the HTML 5 Canvas.
</canvas>
Run Code Online (Sandbox Code Playgroud)
小智 7
如果你想在画布中嵌入边框,那么只需调用:
ctx.strokeRect(0, 0, theCanvas.width, theCanvas.height);
Run Code Online (Sandbox Code Playgroud)
设定后strokeStyle和可选lineWidth.在这种情况下,每次清除画布时都必须更新边框.
如果你只是想在画布周围有一个边框,那么成为画布'位图本身的一部分并不重要(如果你想保存图像)只需将CSS应用到canvas元素:
theCanvas.style.border = '1px solid #000'; // adjust as needed
Run Code Online (Sandbox Code Playgroud)
或直接使用标签中的CSS样式或CSS规则.
演示
我建议相反,虽然在父元素上设置边框(使用CSS规则),因为边框(和填充)可以影响鼠标位置(如果调整)getBoundingClientRect().
演示