我刚刚完成用于图片分析和修复的网络应用程序。我需要 Canvas 方面的帮助。这就是我所做的:
编辑:
<img id="imgEdit" src="<?php echo $imagename; ?>" border="0">
<canvas id="canvasPaint"
width="<?php echo $width; ?>"
height="<?php echo $height; ?>">
</canvas>
<input type="button" value="Clear" onClick="clearCanvas();" class="button">
<input type="button" value="Save" onClick="saveViaAJAX();" class="button">
<div id="debugFilenameConsole">Wait for a while after clicking the button and the filename of the image will be shown to you. </div>
但是现在我的clearCanvas函数遇到了问题。因为浏览器无法读取属性“宽度”。这是我的完整源代码。怎么办,请有人告诉我我做错了什么。
编辑:
function clearCanvas()
{
var theCanvas = document.getElementById("canvasPaint");
if (theCanvas && theCanvas.getContext) {
var ctx = theCanvas.getContext("2d");
if (ctx) {
ctx.clearRect(0, 0, <?php echo $width; ?>, <?php echo $height; ?>);
var srcImg = document.getElementById("imgEdit");
ctx.drawImage(srcImg, 0,0);
clickX = new Array();
clickY = new Array();
clickDrag = new Array();
}}}
function saveViaAJAX()
{
var theCanvas = document.getElementById("canvasPaint");
var canvasData = theCanvas.toDataURL("image/jpg");
var postData = "canvasData="+canvasData;
var ajax = new XMLHttpRequest();
ajax.open("POST",'canvasSave.php',true);
ajax.setRequestHeader('Content-Type', 'canvas/upload');
ajax.send(postData);
}
用户单击“保存图像”后,我需要将 Canvas 另存为本地磁盘上的 jpeg 图像。这意味着, Canvas 中透明的区域会变成黑色背景。
我需要这样的东西: http://i48.tinypic.com/2w5vhpv.jpg
最佳答案
您可以使用 canvas.toDataUrl('image/jpg')
将 Canvas 保存到图像文件中。
关于第一个问题:通常你用 context.clearRect(0, 0, canvas.width, canvas.height)
清除 Canvas 方法。话虽这么说,如果 Canvas 和上下文声明正确,您的代码应该按预期工作。
关于php - 清除 Canvas 并保存 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11693221/