问题
使用canvas绘制了一个表格,想要在上面进行编辑操作,但canvas并不支持修改操作
思路
通过给html元素设置绝对定位,遮盖canvas上的指定位置,所有编辑操作都在元素上进行,也可以将元素的值绘制到canvas上,示例demo如下:
点击查看代码
<!DOCTYPE HTML>
<html>
<style>
</style>
<body style="padding:0px;margin:0px;">
<div style="width:500px; height:500px; position:relative;">
<canvas id="canvas_id" width="500px" height="500px"></canvas>
<input id="input_id" style="top:20px;left:20px;position:absolute;outline:none;border:0px;font-size:20px" readonly=""></input>
</div>
<button onclick="beginEdit()">编辑</button>
<button onclick="cancelEdit()">取消编辑</button>
<button onclick="drawText()">绘制输入框内容</button>
<button onclick="hiddenInput()">隐藏输入框</button>
<button onclick="showInput()">显示输入框</button>
</body>
<script>
var ctx;
window.onload = function(){
ctx = document.getElementById("canvas_id").getContext('2d');
ctx.fillStyle = '#d9ecff';
ctx.font = "20px '微软雅黑'";
ctx.beginPath();
ctx.moveTo(1,1);
ctx.lineTo(1,498);
ctx.lineTo(498,498);
ctx.lineTo(498,1);
ctx.closePath();
ctx.fill();
}
function beginEdit(){
document.getElementById("input_id").removeAttribute("readonly");
document.getElementById("input_id").style.border = "1px solid #000000";
document.getElementById("input_id").focus();
}
function cancelEdit(){
document.getElementById("input_id").setAttribute("readonly",true);
document.getElementById("input_id").style.border = "0px";
}
function drawText(){
ctx.fillStyle = '#000000';
ctx.fillText(document.getElementById("input_id").value,20,20 + 20);
}
function hiddenInput(){
document.getElementById("input_id").style.display = "none";
}
function showInput(){
document.getElementById("input_id").style.display = "";
}
</script>
</html>