我是javascript的新手,我正在尝试从画布中保存签名。当我单击提交按钮时,假设在浏览器中打开一个新窗口并保存画布的内容,但这不起作用。我检查了 isset 以确保按钮正常工作。
代码:
<?php
if(isset($_POST['submit']))
{
?>
<script>
var canvas = document.getElementById("canvas");
var w=window.open('about:blank','image from canvas');
w.document.write("<img src='"+canvas.toDataURL("image/png")+"' alt='from canvas'/>");
</script>
<?php
}
?>
答案 0 :(得分:2)
你可以这样做。从画布中拉出base64图像,将其发布到后端,处理结果(在前端)。
// IGNORE (DRAW STUFF)
// Source: http://www.html5canvastutorials.com/advanced/html5-canvas-get-image-data-url/
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
// draw cloud
context.beginPath();
context.moveTo(170, 80);
context.bezierCurveTo(130, 100, 130, 150, 230, 150);
context.bezierCurveTo(250, 180, 320, 180, 340, 150);
context.bezierCurveTo(420, 150, 420, 120, 390, 100);
context.bezierCurveTo(430, 40, 370, 30, 340, 50);
context.bezierCurveTo(320, 5, 250, 20, 250, 50);
context.bezierCurveTo(200, 5, 150, 20, 170, 80);
context.closePath();
context.lineWidth = 5;
context.fillStyle = '#8ED6FF';
context.fill();
context.strokeStyle = '#0000ff';
context.stroke();
// STOP IGNORING
&#13;
<canvas id="canvas" width="600" height="200"></canvas>
<button onclick="sendImageToBackend()">Send it to backend!</button>
<script>
function getCanvasImage() {
var canvas = document.getElementById('canvas');
return (canvas) ? canvas.toDataURL('image/png') : false;
}
function sendImageToBackend() {
var url = 'save.php';
var dataURL = getCanvasImage();
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
var responseImg;
// Handle response from save.php
if (this.status === 200) {
responseImg = document.createElement('IMG');
responseImg.src = this.responseText;
document.body.appendChild(responseImg);
} else {
console.log('Errorz happened!', this.responseText);
}
};
xhr.send('data=' + encodeURIComponent(dataURL));
}
</script>
&#13;
save.php
<?php
if ($_REQUEST['data']) {
http_response_code(200); // OK
echo "{$_REQUEST['data']}";
} else {
http_response_code(400); // Bad request
echo "Oh, noes! You brokez it!";
}