有个问题和我的很相似here . 我发布这个的原因是因为链接中的一半问题从未得到回答。我处在线条始终一致的位置,但您在绘图时看不到自己在做什么。代码是这样的:
canvas.addEventListener('mousedown', function(e) {
ctx.beginPath();
ctx.moveTo(mouse.x, mouse.y);
canvas.addEventListener('mousemove', onPaint, false);
}, false);
canvas.addEventListener('mouseup', function() {
canvas.removeEventListener('mousemove', onPaint, false);
ctx.stroke();
ctx.closePath();
}, false);
var onPaint = function() {
ctx.lineTo(mouse.x, mouse.y);
};
这很有效,只是我看不到我在画什么。我见过一些人谈论使用临时 Canvas 进行可见的绘制,然后将笔画复制到主 Canvas ,但我还没有看到实际有效的示例。
最佳答案
这是 kinetic.js 的代码:
HTML :
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-16">
<script src="jquery-2.0.3.js" type="text/javascript"></script>
<script src="cn.js" type="text/javascript"></script>
<script src="kinetic.js" type="text/javascript"></script>
<style>
</style>
</head>
<body>
<div id="container" height="300px" style="width:300px;height:300px;border:3px solid"></div>
</body>
</html>
cn.js :
$(function()
{
var lineSx,lineSy,lineFx,lineFy;
var ismouseDown=false;
var line;
var layerList=new Array();
setInterval(function(){// for clearing the temp layer
var l=null,topLayer;
var i=1;
l=layerList.pop();
while(l){
//console.log(l);
if(i!=1){
l.destroy();
l=null;
}
else{
topLayer=l;
}
l=layerList.pop();
i++;
}
layerList.push(topLayer);
},2);
var stage = new Kinetic.Stage({
container: 'container',
width: 300,
height: 300
});
var layer = new Kinetic.Layer();
var rect = new Kinetic.Rect({
x: 0,
y: 0,
width: 300,
height: 300,
fill: 'black',
});
rect.on("mousedown",function(e){
console.log(e);
ismouseDown=true;
lineSx=e.clientX;
lineSy=e.clientY;
});
rect.on("mousemove",function(e){
if(ismouseDown){
console.log(e);
var cx=e.clientX;
var cy=e.clientY;
var tempLayer = new Kinetic.Layer();
//stage.remove(tempLayer);
line=createLine(lineSx,lineSy,cx,cy);
tempLayer.add(line);
stage.add(tempLayer);
layerList.push(tempLayer);
}
});
rect.on("mouseup",function(e){
ismouseDown=false;
console.log(e);
lineFx=e.clientX;
lineFy=e.clientY;
line=createLine(lineSx,lineSy,lineFx,lineFy);
layer.add(line);
stage.add(layer);
});
layer.add(rect);
stage.add(layer);
});
function createLine(sx,sy,fx,fy){
var line = new Kinetic.Line({
points: [sx,sy,fx,fy],
stroke: 'white',
strokeWidth: 3,
lineCap: 'round',
lineJoin: 'round'
});
return line;
}
关于javascript - 用鼠标在 Canvas 上绘制不透明的线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20087156/