我有一个表格,里面有这样的图像:
<body>
<form action="" method="POST" id="canvas">
<img src="/foo/bar.jpg" width="350" height="350" id="imageId"/>
<input type="submit" name="submit" value="Label" id='input'>
</form>
</body>
使用JavaScript,我希望能够使用坐标保存图像的一部分,我正在寻找类似的东西:
Save_Image(x, y, x2, y2, name_of_new_cropped_image_to_be_saved);
是否存在类似的东西?
答案 0 :(得分:0)
您可以尝试使用画布:
function cropImage(src, x, y, w, h) {
var canvas = document.createElement("canvas");
//document.body.appendChild(canvas); // for testing
var ctx = canvas.getContext("2d");
canvas.width = w;
canvas.height = h;
ctx.fillRect(0, 0, w, h);
ctx.drawImage(src, -x, -y);
return {
save: function(filename) {
var a = document.createElement("a");
canvas.toBlob(function(blob) {
a.href = window.URL.createObjectUrl(blob);
a.download = filename;
a.click();
});
//console.log(a);
}
}
}
var img = document.querySelector("img");
document.getElementById("save").onclick = function () {
cropImage(img, 50, 20, 100, 80).save("test");
}
body {
background: black;
overflow: auto;
}
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAADIBAMAAAA0O6rRAAAAG1BMVEX///8zPtvMzvZmbuSZnu1/hujl5vqytvFMVt+W5DZNAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAFLUlEQVR4nO2bzXfbRBTFHdmWvESYFC9jpzQsMWk5XSYk0C5r6Cks5dADW2ySlmXNKdR/djWSP2Y0741G9juVHO5vFc2Mdd+VNPNGM0qrBQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAuDecnp9/ex80WsM4/vw+aMBI0zRgpGkaMNI0DRhpmgaMNE0DRpqmASNN04CRpmnASNM0/l9GwrO3128fuRqM0gZztkVDjERXccbgl4RuEKwaxPGTZ2STZhi5izcc/0k1+CrWGDw+2UFDgjKRv40wCSdGg+zGVdbYi851ziS90NcaPzrD7CfF8/wWW3xZUWM/juwAzCj0MAfn50+p6rQDrX+3XC6sU/hpfAojQRbc+zfq7/AuO7gwT3OZP03ZgBWeXS0aamSmSl6tj6Jx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Whg1jcT9+eYwUM8i9TC6NMQIs2AfP0qyb9sLHXWWr+c+y759v7nNvvQvGEkLXs6T7Mv4fBk7qaghxsyxYxBsVtmXy83WwbZ6Etu8ahG4NMSIXCLZ5/Am2rQpfG7VfqiuIcapSyQam4EOzN79sGD0/S4aYvxFXu4V4ZUew8sTV3VhDPPWEGO9S/Pv92Rt/v8t8YD+p7bw9inn0l9DjPDmbD5K2Oqb0dnod9evR3NXvZcGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAtnwEVtQcr5fCNI0AAAAASUVORK5CYII=">
<!-- need to encode image because of CORS -->
<button id="save">save cropped - 50, 20, 100, 80</button>
不幸的是,Edge不支持HTMLCanvasElement.toBlob()
(我使用Edge):(。您可以使用polyfill from MDN。如果我的代码不起作用,请发表评论。toBlob
应该可以在带有前缀的IE 10中使用。最低Chrome为50