我正在嘗試在我的網頁中僅使用JavaScript插入「自由繪製框」。我已經能夠讓我的'自由繪製盒子腳本'在HTML上呈現,但我想通過JavaScript代替HTML來實現。我已經包含了我的整個代碼片段,但是,我相信所討論的代碼是對底部註釋的「插入HTML」。我的錯誤在哪裏?通過JavaScript插入HTML
<html>
<script type="text/javascript">
/*Free Draw Box Script*/
var canvas, ctx, flag = false,
prevX = 0,
currX = 0,
prevY = 0,
currY = 0,
dot_flag = false;
var x = "black",
y = 2;
function init() {
canvas = document.getElementById('can');
ctx = canvas.getContext("2d");
w = canvas.width;
h = canvas.height;
canvas.addEventListener("mousemove", function (e) {
findxy('move', e)
}, false);
canvas.addEventListener("mousedown", function (e) {
findxy('down', e)
}, false);
canvas.addEventListener("mouseup", function (e) {
findxy('up', e)
}, false);
canvas.addEventListener("mouseout", function (e) {
findxy('out', e)
}, false);
}
function draw() {
ctx.beginPath();
ctx.moveTo(prevX, prevY);
ctx.lineTo(currX, currY);
ctx.strokeStyle = x;
ctx.lineWidth = y;
ctx.stroke();
ctx.closePath();
}
function erase() {
var m = confirm("Are you sure you want to clear the Signature?");
if (m) {
ctx.clearRect(0, 0, w, h);
document.getElementById("canvasimg").style.display = "none";
}
}
function save() {
document.getElementById("canvasimg").style.border = "2px solid";
var dataURL = canvas.toDataURL();
document.getElementById("canvasimg").src = dataURL;
document.getElementById("canvasimg").style.display = "inline";
}
function findxy(res, e) {
if (res == 'down') {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
flag = true;
dot_flag = true;
if (dot_flag) {
ctx.beginPath();
ctx.fillStyle = x;
ctx.fillRect(currX, currY, 2, 2);
ctx.closePath();
dot_flag = false;
}
}
if (res == 'up' || res == "out") {
flag = false;
}
if (res == 'move') {
if (flag) {
prevX = currX;
prevY = currY;
currX = e.clientX - canvas.offsetLeft;
currY = e.clientY - canvas.offsetTop;
draw();
}
}
}
/*Insert HTML*/
document.body.innerHTML += '
<body onload="init()">
<canvas id="can" width="800" height="200"
style="position:absolute;top:10%;left:10%;border:1px solid;">
</canvas>
<img id="canvasimg" style="position:absolute;top:10%;
left:52%;" style="display:none;">
<input type="button" value="clear" id="clr" size="23"
onclick="erase()" style="position:absolute;top:55%;
left:15%;">
</body>
';
</script>
<body>
<p></p>
</body>
</html>
「/」引用的字符串不支持多行,你需要使用'在這種情況下 – tibetty
jQuery絕對沒有必要插入HTML使用g JavaScript。 JavaScript有很多內置的,廣泛支持的功能,可以在沒有任何外部庫或框架的情況下執行此操作。 – Adrian