在Javascript中将可编辑文本框添加到画布元素
我有一个允许人们画画的HTML页面。这很简单。它的代码包含在下面 我正在尝试添加一个按钮,该按钮插入可编辑的文本,并且可以在canvas元素中调整大小 我尝试了许多选择,但没有成功。有没有办法在Javascript中实现这一点 我的守则如下:在Javascript中将可编辑文本框添加到画布元素,javascript,html,jquery,dom-events,Javascript,Html,Jquery,Dom Events,我有一个允许人们画画的HTML页面。这很简单。它的代码包含在下面 我正在尝试添加一个按钮,该按钮插入可编辑的文本,并且可以在canvas元素中调整大小 我尝试了许多选择,但没有成功。有没有办法在Javascript中实现这一点 我的守则如下: <head> <meta charset="utf-8"> <title> Web Paint! </title> <meta nam
<head>
<meta charset="utf-8">
<title>
Web Paint!
</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#draw{
border-color: yellow;
}
</style>
</head>
<body>
<input id="hex" placeholder="enter hex color"></input>
<canvas id="draw"></canvas>
<script>
var canvas = document.getElementById("draw");
var ctx = canvas.getContext("2d");
//resize();
// resize canvas when window is resized
function resize() {
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
}
// initialize position as 0,0
var pos = { x: 0, y: 0 };
// new position from mouse events
function setPosition(e) {
pos.x = e.clientX-160;
pos.y = e.clientY-5;
}
function draw(e) {
if (e.buttons !== 1) return; // if mouse is not clicked, do not go further
var color = document.getElementById("hex").value;
ctx.beginPath(); // begin the drawing path
ctx.lineWidth = 20; // width of line
ctx.lineCap = "round"; // rounded end cap
ctx.strokeStyle = color; // hex color of line
ctx.moveTo(pos.x, pos.y); // from position
setPosition(e);
ctx.lineTo(pos.x, pos.y); // to position
ctx.stroke(); // draw it!
}
// add window event listener to trigger when window is resized
window.addEventListener("resize", resize);
// add event listeners to trigger on different mouse events
document.addEventListener("mousemove", draw);
document.addEventListener("mousedown", setPosition);
document.addEventListener("mouseenter", setPosition);
</script>
</body>
网络绘画!
#画{
边框颜色:黄色;
}
var canvas=document.getElementById(“draw”);
var ctx=canvas.getContext(“2d”);
//调整大小();
//调整窗口大小时调整画布大小
函数resize(){
ctx.canvas.width=window.innerWidth;
ctx.canvas.height=window.innerHeight;
}
//将位置初始化为0,0
var pos={x:0,y:0};
//来自鼠标事件的新位置
功能设置位置(e){
位置x=e.clientX-160;
位置y=e.clientY-5;
}
功能图(e){
if(e.buttons!==1)return;//如果未单击鼠标,则不要继续
var color=document.getElementById(“十六进制”).value;
ctx.beginPath();//开始绘制路径
ctx.lineWidth=20;//线宽
ctx.lineCap=“圆形”//圆形端盖
ctx.strokeStyle=color;//行的十六进制颜色
ctx.moveTo(pos.x,pos.y);//从位置
设定位置(e);
ctx.lineTo(位置x,位置y);//位置
stroke();//画出来!
}
//添加窗口事件侦听器以在调整窗口大小时触发
addEventListener(“调整大小”,调整大小);
//添加事件侦听器以在不同的鼠标事件上触发
文件。添加文件列表(“mousemove”,draw);
文件。添加了文本列表(“鼠标向下”,设置位置);
文件。添加的列表器(“鼠标指针”,设置位置);
请您解释一下上述代码的作用,或者在您的代码中,您的问题出在哪里?你到底是怎么解决这个问题的?此外,你能给我们一个可以重现问题的工作环境吗?上面的代码基本上只是一个画布元素,带有一些js代码,可以让你在移动鼠标时在上面画画。我已经尝试将文本元素添加到canvas元素并使其可编辑,但它不起作用。我对javascript并没有太多经验。这是JSFIDLE:,您可以通过单击并将鼠标移到十六进制代码文本字段旁边的小框来绘制。当我单击您的链接时,它会显示空的空白FIDLE。你确定这是小提琴的正确链接吗?你把小提琴留着了吗?哦,我的错。看看这是否管用:你试过这个吗?