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>

效果如下,(背景颜色是另外的样式)

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-06-16
var canvasDom = $("myCanvas");
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>
}本回答被提问者采纳
第2个回答  2018-07-20
用beginpath()和closepath()分离一下,同一个画布可以写多组这个,颜色也可以选
第3个回答  2011-11-06
我也遇到了这个问题,汗,不知道怎么办呢。
确切的说,用canvas.stroke()之后,改变了strokeStyle,再用canvas.stroke(),会把新的颜色叠加到原来的颜色上,真奇怪。

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网