繁体   English   中英

如何使用HTML Canvas在图像上绘制图像?

[英]How can I draw on top of image using HTML Canvas?

我正在寻求一种“图像中的颜色”效果。

我有几张长颈鹿头像 ,所有的着色都不同。 我希望能够通过使用鼠标绘制形状来显示着色的图像来“着色”图像,并且仅显示交叉点。 长颈鹿的未着色图像默认显示的位置,并且如果使用鼠标在图像上方绘制,则在绘制的位置会显示长颈鹿的着色图像,从而显示图像的某种“着色”。

到目前为止,这就是我所拥有的。 我正在使用Canvas globalCompositeOperationMDN文档作为参考。 但是我还处于初期阶段:

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在我的项目环境中工作,但由于某种原因不在Fiddle中工作。

-更新:我可以使用剪辑将有色图像以长颈鹿的形状“绘制”到长颈鹿的屏幕上。 但是,当我之前渲染未着色的图像时,“着色”效果不起作用。

弄清楚了! 看起来就像是具有两个分层画布元素的clip() ,而不是globalCompositeOperation

以下代码实现了这种“着色”效果

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);
}

暂无
暂无

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

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