我正在构建一个应用程序,将手机外壳与设计重叠,并将最终图像保存到文件夹中。下面的代码工作并显示在浏览器中,但我希望能够在加载页面后立即自动保存图像。目标是使用cron运行此脚本,以便生成并自动保存图像。
我尝试过使用canvas.toDataURL和canvas2image没有成功?我究竟做错了什么?我如何实现它?
(function () {
var canvas = document.getElementById('canvas');
canvas.width = 403;
canvas.height = 800;
var ctx = canvas.getContext("2d");
$.when(
loadImage('./img/pattern.jpg'),
loadImage('./img/iphone_mask.png'),
loadImage('./img/iphone_overlay.png')
).then( function (patternImage, maskImage, overlayImage){
ctx.save();
ctx.drawImage(maskImage, 0, 0);
ctx.globalCompositeOperation = "source-in";
ctx.drawImage(patternImage, 0, 0);
ctx.globalCompositeOperation = "destination-atop";
ctx.restore();
ctx.drawImage(overlayImage, 0, 0);
}
);
function loadImage(url){
var promise = $.Deferred();
var image = new Image();
image.src = url;
image.onload = function(){
promise.resolve(image);
};
image.onerror = promise.reject;
return promise;
}
})();
<!doctype html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<link rel="stylesheet" href="styles/main.css">
</head>
<body>
<canvas id='canvas'></canvas>
<script src="lib/jquery.min.js"></script>
<script src="js/script.js"></script>
</body>
</html>
`
答案 0 :(得分:0)
以下代码将为您提供base64编码的图像,您可以将其设置为img标记的源,用户可以在其中保存图像,或通过AJAX将其发送到服务器端代码,该代码可以将图像写入一个文件夹。
//save canvas image as data url (png format by default)
var dataURL = canvas.toDataURL();
//Set it as the source of an img tag
$('#img').attr('src', dataURL);
//Send it via AJAX
$.post('handlerUrl', { image: dataURL }, function(response) {
//Do something
});
您无法通过JavaScript将其保存到文件夹中。