繁体   English   中英

HTML5 画布图层显示

[英]HTML5 Canvas Layer Display

我正在使用 HTML5 画布编写一个简单的图像操作/绘图实用程序。 它目前适用于单个画布层。

我正在尝试添加一个“预览”功能,这样当光标在画布上移动时显示的不是光标,而是显示在该位置单击鼠标的效果。 例如,如果您在主画布中加载了一个图像,并且选定的 globalCompositeOperation 为饱和度,您可以通过将鼠标移动到不同部分来预览图像的外观。 预览是当前工具的大小,所以如果它是一个圆工具,半径为 5,您会看到为该圆覆盖的任何内容渲染的效果。 如果不单击,则只能看到预览。 如果单击向下,效果将应用于预览中显示的区域中的画布。

我的主画布上有一个用于 mousemove、mouseup 和 mousedown 的事件侦听器。 这是我当前的代码(JS 和 CSS)。 有两个画布标签(下面的代码中未显示)。 一个是我的带有context ctx的主画布,另一个是带有context mouseCtx的鼠标预览画布。 CS 指的是全局“画布状态”对象。

代码现在可以正常运行,除了鼠标预览出现在主画布上的任何元素后面(鉴于较低的 z-index,我期望它)。 当我点击放置一个元素时,它会弹出所有内容的前面。 但是,如果我给鼠标悬停一个更高的 Z-index,主画布上根本不会显示任何内容。

我是否遗漏了一些愚蠢的东西,或者我实施此功能的策略是否遥遥无期? 非常感谢您对正确方向的任何提示。

 canvas.addEventListener('mousemove', mouseTrack); canvas.addEventListener('mousedown', mouseTrack); canvas.addEventListener('mouseup', mouseTrack); function mouseTrack(e) { (e.type === 'mousedown') ? CS.isDrawing = true: 0; (e.type === 'mouseup') ? CS.isDrawing = false: 0; let mouseParams = { x: e.layerX, y: e.layerY, movArr: [e.movementX, e.movementY], windowArr: [e.clientX, e.clientY] }; if (CS.isDrawing === false) { mouseCtx.clearRect(0, 0, mouseLayer.width, mouseLayer.height); mouseCtx.drawImage(canvas, 0, 0); //copy the current canvas console.log((CS.isDrawing === true) + " is drawing"); mouseCtx.strokeStyle = CS.strokeS || randomRGBA(); mouseCtx.fillStyle = CS.fillS || randomRGBA(); mouseCtx.globalAlpha = CS.lOpacity; mouseCtx.beginPath(); //draw the thing on the current canvas switch (CS.tool) { case 'tBrush': drawBrush(mouseParams, mouseCtx, CS.brush, CS.brushSize); break; case 'tLine': drawLine(mouseParams, mouseCtx); break; case 'tCurve': drawBezier(mouseParams, mouseCtx); break; case 'tCircle': drawCircle(mouseParams, mouseCtx); break; case 'tSquare': drawSquare(mouseParams, mouseCtx); break; } } else { ctx.drawImage(mouseLayer, 0, 0); } }
 canvas { position: absolute; left: 0px; top: 0px; border: 2px solid green; outline: none; -webkit-user-select: none; /* Chrome all / Safari all */ -moz-user-select: none; /* Firefox all */ -ms-user-select: none; /* IE 10+ */ user-select: none; cursor: none; z-index: 1; } canvas.mouseOverlay { position: absolute; left: 0px; top: 0px; border: 2px solid green; outline: none; -webkit-user-select: none; /* Chrome all / Safari all */ -moz-user-select: none; /* Firefox all */ -ms-user-select: none; /* IE 10+ */ user-select: none; cursor: none; z-index: 0; }

可能发生的情况是,您的预览画布妨碍了在主画布上触发事件。 您是否检查过主画布上的mousedown事件是否被触发? 如果确实没有被触发,请尝试添加pointer-events:none; 到您的canvas.mouseOver css(z-index 更高)。

注意:如果您需要支持旧版本的 IE,这可能是一个糟糕的解决方案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM