-2

我有一个网页,它使用drawimage(x,z,width,height). 用户可以通过单击线在图像上的任何给定线周围绘制一个矩形。然后在图像上使用rect(x,y,w,h).

使用 JavaScript 放大镜,用户可以将鼠标悬停在图像上以查看放大版本。但是,它不会显示在画布上的图像上绘制的矩形。

是否可以同时绘制矩形和图像?目前这是放大镜的设置:

//  - Setup the magnifier component
var  glass, w, h, bw;
glass = document.getElementById("magnifier");     // Get pre-existing div for the magnifier
glass.setAttribute("class", "img-magnifier-glass");

// Set background properties for the magnifier glass:
glass.style.backgroundImage = 'url("' + pRow.getValue("imgPath") + '")'; // pRow here refers to a parameter array that is passed in containing data about the image and rectangle
glass.style.backgroundRepeat = "no-repeat";
glass.style.backgroundSize = imgwidth + "px " + imgheight + "px";
     bw = 3;     // Border width of the magnifier glass.
     w = glass.offsetWidth / 2;
     h = glass.offsetHeight / 2;

稍后有实际移动背景位置的代码。但我没有看到一种方法来显示在图像顶部、画布中、放大镜上绘制的矩形。

4

1 回答 1

-1

最后我解决了这个问题,这是一项相当艰巨的任务。

去做吧

  • 我不得不画一个离屏画布
  • 然后在这个新画布上复制当前主图像并在矩形上绘制
  • 在 URL 中序列化结果
  • 然后将此 URL 传递给放大镜背景图像属性

每次您想要更改矩形位置时,这确实会引入较长的加载时间。但允许矩形成为图像的一部分,以便放大镜将其拾取。

这是代码(这是在Omnis Studio中完成的,如果有任何与普通 JavaScript 不同的东西(在此之前也有很多代码。但这是解决方案,所以我将只展示这一点)):

// Draw the same orange box, but on the original image size
var img = document.getElementById('jp')  // The master image. It will
                                         // have been already loaded by now

// Create an offscreen canvas, put the image and then the bounding box
//var mc = document.createElement("canvas")

// Get an offscreen canvas. Saves from having to create it each time
var mc = document.getElementById('offscreenCanvas')

// Make the canvas the same size as the master image.
// Otherwise, whatever we render will be truncated.
mc.width = imgwidth
mc.height = imgheight

// Get the drawing context for this offscreen canvas
var mctx = mc.getContext("2d")

// Erase the previous box (if any)
mctx.clearRect(0, 0, mc.width, mc.height)

// Draw the full image onto our magnifier canvas, starting at (0, 0)
mctx.drawImage(img, 0, 0, imgwidth, imgheight)

mctx.beginPath()     // Create our selection box
mctx.strokeStyle = "orange"//
mctx.lineWidth = 8     // Because we're "zoomed in", make this line a little thicker
boxX = pRow.getValue("x")     // Top left x coordinate - unscaled coordinates
boxY = pRow.getValue("y")     // top left y coordinate
boxW = pRow.getValue("width")     // Distance right
boxH = pRow.getValue("height")     // Distance down
mctx.rect(boxX, boxY, boxW, boxH)
mctx.stroke()

// Serialise the result of overlaying the box on the image
var r_img = mc.toDataURL("image/png")
//   window.location = r_img     // Debugging ... open image in a new
                                 // window window.open(r_img, "toDataURL() image")

// Get pre-existing div for the magnifier
glass = document.getElementById("magnifier")

// Our rendered image
glass.style.backgroundImage = "url(" + r_img + ")"

如果有人能找到一种方法来做到这一点,而无需不断地重新加载图像并导致大量的延迟/等待时间。请告诉我。

于 2020-08-14T04:22:21.520 回答