我正在寻求实现某种“图像中的颜色”效果。
我有几张giraffes head的图像,所有图像都带有不同的颜色。我希望能够通过使用鼠标绘制形状来显示着色的图像来“着色”图像,并且仅显示交叉点。长颈鹿的未着色图像默认显示的位置,并且如果使用鼠标在图像上方绘制,则在绘制的位置会显示长颈鹿的着色图像,从而显示图像的某种“着色”。
这是我到目前为止所拥有的。我使用MDN documentation of Canvas globalCompositeOperation作为参考。但是我还处于初期阶段:
function animate() {
// canvasContext.clearRect(0, 0, canvas.width, canvas.height);
// canvasContext.drawImage(image2, (canvas.width/2) - (image2.width/2), (canvas.height/2) - (image2.height/2), image2.width, image2.height); // if this line is removed, we can draw the image, but theres no starting image
canvasContext.save();
canvasContext.beginPath();
canvasContext.arc(touchX, touchY, 20, 0, Math.PI*2, false);
canvasContext.clip();
canvasContext.drawImage(image1, (canvas.width/2) - (image1.width/2), (canvas.height/2) - (image1.height/2), image1.width, image1.height);
canvasContext.restore();
window.requestAnimationFrame(animate);
}
我什至无法让椭圆“刷子”留在画布上并填充长颈鹿的形状。似乎对我没有任何帮助。
这里JSFiddle无效。 touchmove
在我的项目环境中工作,只是出于某种原因不在小提琴中工作。
- 更新:我可以使用剪辑将有色图像以长颈鹿的形状“绘制”到长颈鹿的屏幕上。但是当我之前渲染未着色的图像时,“着色”效果不起作用。
答案 0 :(得分:-1)
想通了!答案似乎是clip()
,其中包含两个分层的画布元素,而不是globalCompositeOperation。
以下代码实现了this 'colouring in' effect。
function handleOnPointerDown(event) {
touchX = event.touches[0].clientX;
touchY = event.touches[0].clientY;
}
function animate() {
displayImageOnCanvas(canvas, canvasContext, loadedImage[0]);
canvasContext2.save();
canvasContext2.beginPath();
canvasContext2.globalAlpha = 0.5;
canvasContext2.arc(touchX, touchY, 20, 0, Math.PI*2, false);
canvasContext2.clip();
if (colourState === 1) {
// red tinted
displayImageOnCanvas(canvas2, canvasContext2, loadedImage[1]);
} else if (colourState === 5) {
// blue tinted
displayImageOnCanvas(canvas2, canvasContext2, loadedImage[5]);
}
canvasContext2.restore();
window.requestAnimationFrame(animate);
}