HTML5 canvas lineTO()方法如何在同一个画布画不同粗细的,颜色的线条出来
canvas.lineWidth=1;
canvas.strokeStyle='#000000';
canvas.lineTo();
canvas.stroke();
///结束上次绘画,然后再开始下次绘画,设置线宽和颜色。
canvas.beginPath();
canvas.lineWidth=2;
canvas.strokeStyle='red';
canvas.lineTo();
canvas.stroke();
///再次结束,开始,设置粗细和颜色。
canvas.beginPath();
canvas.lineWidth=1;
canvas.strokeStyle='#000000';
这样就可以了。保证不会出现在叠加现象。 展开
是这样的,建议在同一画布上绘制不同模块时,记得使用 beiginPath()和closePath()框选起来,在里面使用stroke.style可以画不同颜色的东西
<script >
window.onload=function(){
var myCarvas=document.getElementById('my-carvas')//mycarvas画布的id
var ctx=myCarvas.getContext('2d');
//绘制矩形
ctx.beginPath();
ctx.fillStyle='#ff0000';//填充颜色
ctx.fillRect(5,5,100,100);//填充矩形 X Y width height
ctx.strokeStyle='blue';//边框颜色
ctx.lineWidth='5';//边框宽度
ctx.strokeRect(5,5,100,100)//边框起点X,Y width height
ctx.closePath();
//基础线条
ctx.beginPath();
ctx.lineTo(150,150)
ctx.lineTo(250,150)
ctx.lineTo(200,250)
ctx.strokeStyle='darkgreen';
ctx.closePath();
ctx.stroke();
}
</script>
效果如下,(背景颜色是另外的样式)
var myDraw1 = new Draw(canvasDom);
$("button_line").onclick = function(){
canvasDom.onmousemove = function(e){
myDraw1.drawLine(e);
}
}
$("button_line_width").onclick = function(){
myDraw1.setLineWidth($("text_line_width").value);
}
$("button_choose_color").onclick = function(){
myDraw1.chooseColor($("text_choose_color").value);
}
function Draw(canvasDom){
var mouseX,mouseY,mx,my;
var pd = false;
var coordinate = function(e){
mouseX = e.pageX-canvasDom.offsetLeft;
mouseY = e.pageY-canvasDom.offsetTop;
}
canvasDom.onmousedown = function(e){
coordinate(e);
pd = true;
mx = mouseX;
my = mouseY;
ctx.save();
}
canvasDom.onmousemove = function(e){
drawLine(e);
}
canvasDom.onmouseup = function(e){
pd = false;
}
this.drawLine = function(e){
coordinate(e);
if(pd == true){
ctx.save();
ctx.beginPath();
ctx.moveTo(mx,my);
ctx.lineTo(mouseX,mouseY);
ctx.closePath();
ctx.stroke();
mx=mouseX;
my=mouseY;
}
}
this.setLineWidth = function(lw){ctx.lineWidth = lw;}
this.chooseColor = function(c){ctx.strokeStyle = c;}
<!--html-->
<canvas id="myCanvas" width="400" height="400" style="border:solid 1px #000;"></canvas><br>
<input type="button" value="画线" id="button_line">
<input type="text" id="text_line_width" for="button_line_width"><input id="button_line_width" type="button" value="设置线宽"><br>
<input type="text" id="text_choose_color"><input type="button" value="改变颜色" id="button_choose_color"><br>
}
2018-07-20
确切的说,用canvas.stroke()之后,改变了strokeStyle,再用canvas.stroke(),会把新的颜色叠加到原来的颜色上,真奇怪。