【发布时间】:2013-12-26 19:16:48
【问题描述】:
我试图让用户通过在画布上绘制半透明线条的“绘画”工具在区域上绘画来指定区域。其目的是为将在画布下方绘制的图像指定一个“蒙版”。
这是我迄今为止尝试过的:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var canvasPos = canvas.getBoundingClientRect();
var dragging = false;
drawImage();
$(canvas).mousedown(mouseDown);
$(canvas).mouseup(mouseUp);
$(canvas).mousemove(mouseMove);
function drawImage() {
var img = new Image();
img.src = 'http://img2.timeinc.net/health/img/web/2013/03/slides/cat-allergies-400x400.jpg';
img.onload = function () {
ctx.drawImage(img, 0, 0);
};
}
function mouseDown(e) {
var pos = getCursorPosition(e);
dragging = true;
ctx.strokeStyle = 'rgba(0, 100, 0, 0.25)';
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.lineWidth = 15;
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
}
function mouseUp(e) {
dragging = false;
}
function mouseMove(e) {
var pos, i;
if (!dragging) {
return;
}
pos = getCursorPosition(e);
ctx.lineTo(pos.x, pos.y);
ctx.stroke();
}
function getCursorPosition(e) {
return {
x: e.clientX - canvasPos.left,
y: e.clientY - canvasPos.top
};
}
- 链接到上述代码的jsfiddle:http://jsfiddle.net/s34PL/2/
此示例代码的问题在于,随后绘制的像素使不透明度变得越来越不可见。我认为这是因为这条线是 15 像素宽(但我希望它那么宽)。
我该如何解决这个问题?
谢谢!
【问题讨论】:
-
Kangax wrote an awesome blog post on this topic 最近。
-
@Pointy,我在发布这个问题之前实际上已经阅读了它。确实是一篇很棒的 帖子,学到了很多东西——但我没有找到针对我的特定问题的解决方案?
标签: javascript html canvas drawing html5-canvas