在此先感谢您的帮助。
我正在使用openseadragon库。主要思想是选择可缩放图像的一部分并将其复制到已经定义的 Canvas 上。为了做到这一点,我试图使用功能canvas.getcontext('2d')。DrawImage(),但是为此,我需要将openseadragon的viwer实例转换为图像,并且在这一点上失败了。
这是转换:imageObj.src = viewer.canvas.toDataURL();
这是完整的代码:
<body>
<div>
<div id="formulario" style="formulario">
<form name="form" method="post" action="">
<div>
<canvas id="imagen" style="imagenCont">
</canvas>
</div>
</form>
<p id="pruebax">(0,0)</p>
<p id="pruebay">(1,0)</p>
<p id="pruebaw">(1,1)</p>
<p id="pruebah">(0,1)</p>
<p id="centro">c</p>
</div>
<div id="map" class="openseadragon">
<script type="text/javascript">
var viewer = OpenSeadragon({
id: 'map',
prefixUrl: 'openseadragon/images/',
tileSources: 'borde_de_salida_full.dzi',
showNavigator: true,
});
var selection = viewer.selection({
onSelection: function(rect){
document.getElementById("pruebax").textContent='('+rect.x+','+rect.y+')';
document.getElementById("pruebay").textContent='('+(rect.x+rect.width)+','+rect.y+')';
document.getElementById("pruebaw").textContent='('+(rect.x+rect.width)+','+(rect.y+rect.height)+')';
document.getElementById("pruebah").textContent='('+rect.x+','+(rect.y+rect.height)+')';
document.getElementById("centro").textContent='('+((rect.x+rect.width)/2)+','+((rect.y+rect.height)/2)+')';
var canvas = document.getElementById('imagen');
var context = canvas.getContext('2d');
var imageObj = new Image();
imageObj.src = viewer.canvas.toDataURL();
var overlay = viewer.canvasOverlay({
clearBeforeRedraw:true,
onRedraw:function(){
overlay.context2d().strokeStyle = "red";
overlay.context2d().lineWidth = 35;
overlay.context2d().strokeRect(rect.x, rect.y, rect.width , rect.height);
context.drawImage(imageObj, rect.x, rect.y, rect.width, rect.height, rect.x, rect.y, rect.width, rect.height); //cambiar tamaño del destino a posteriori.
}
});
selection.toggleState()=false;
}
});
</script>
</div>
</div>
</body>
谢谢
最佳答案
从openseadragon选择中获取选定的图像
var selection = viewer.selection({
onSelection: function(rect){
var viewportRect = viewer.viewport.imageToViewportRectangle(rect);
var webRect = viewer.viewport.viewportToViewerElementRectangle(viewportRect);
const { x, y, width, height } = webRect || {};
const { canvas } = viewer.drawer;
let source = canvas.toDataURL();
const img = new Image();
img.onload = () => {
let croppedCanvas = document.createElement('canvas');
let ctx = croppedCanvas.getContext('2d');
croppedCanvas.width = width;
croppedCanvas.height = height;
const pixelDens = OpenSeadragon.pixelDensityRatio;
ctx.drawImage(img, x*pixelDens, y*pixelDens, width*pixelDens, height*pixelDens, 0, 0, width, height);
let croppedSrc = croppedCanvas.toDataURL();
fetch(croppedSrc)
.then(res => res.blob())
.then(blob => {
const file = new File([blob], "File name", { type: "image/png" })
// you can get selected cropped image file here
})
}
img.src = source;
}
})