HTML 5:在鼠标点击位置上从画布中删除颜色

时间:2018-10-02 15:06:45

标签: javascript html5 canvas html5-canvas

我有一个<canvas>,背景全覆盖着它下面的另一个html元素。

我想要实现的是: 当我将鼠标移到画布上并单击按钮时,我想要使该画布的圆形区域(具有预定义的半径,即鼠标光标所在的位置)变得透明。

由于我是初次画画布,所以我真的不知道该怎么做。 所以我的第一个想法是使用context.createImageData(canvas.width, canvas.height),用黑色填充图像,然后context.putImageData(imageData)将其粘贴到画布上。

我以为我可以获取画布鼠标坐标并使该圆圈内的所有像素透明。但是我不确定如何确定属于该圆的所有像素,这是否是最有效的方法。

在实现此目标方面的任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:3)

您要寻找的是画布上下文的globalCompositeOperation属性。设置该属性会影响绘制新形状与先前形状交互的方式。将其设置为“目标输出”,之后绘制的形状将从先前绘制的形状中雕刻出来。

这里是一个例子:

var canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");

//fill canvas with black
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);

//carve circle out of it
ctx.globalCompositeOperation = "destination-out";
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 70;
ctx.beginPath();
ctx.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = "white";
ctx.fill();
<div style="width: 500px; height: 300px; position: relative;">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam mollis orci vitae ex viverra, eu consequat diam pharetra. Maecenas quis odio eget eros imperdiet porttitor. Nam at condimentum arcu, eget eleifend metus. In vehicula varius justo a aliquet. Etiam ac mollis justo. Nunc dapibus massa magna, nec rhoncus arcu aliquam a. Proin condimentum sem vitae dui interdum, at congue massa blandit. Phasellus fringilla velit ultrices, suscipit risus ac, commodo justo. Pellentesque sed leo massa.

Integer non magna iaculis, aliquet odio vitae, semper felis. Aliquam ultrices cursus elementum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aenean auctor felis purus, eu eleifend neque sodales eget. Donec eu mattis erat. Morbi libero ante, ornare eget scelerisque vel, placerat quis nulla. Maecenas congue cursus purus, at placerat libero finibus vel. Interdum et malesuada fames ac ante ipsum primis in faucibus. Suspendisse dignissim neque sapien, et scelerisque mi efficitur vitae. Nam bibendum felis eu leo venenatis, ac semper sem sagittis. Fusce suscipit varius orci. Sed ut mi justo.

<canvas width="500" height="300" style="position: absolute; top: 0; left: 0;"></canvas>
</div>

答案 1 :(得分:1)

我使用合成和destination-out选项为您创建了一个JSFiddle,它将把形状当作倒置蒙版。

https://jsfiddle.net/ytbfnpa9/

const MASK_RADIUS = 50

const myCanvas = document.getElementById('myCanvas')
const bounds = myCanvas.getBoundingClientRect()
const ctx = myCanvas.getContext('2d')

function drawCircleMask(x, y, r) {
    ctx.beginPath()
    ctx.arc(x, y, r, 0, 2 * Math.PI)
  ctx.fill()
}

ctx.fillStyle = '#000000'
ctx.fillRect(0, 0, 200, 200)

/**
* Use compositing to treat shapes as masks
*/
ctx.globalCompositeOperation = 'destination-out'

myCanvas.addEventListener('click', e => {
    const x = e.clientX - bounds.left
  const y = e.clientY - bounds.top

  drawCircleMask(x, y, MASK_RADIUS)
})