2017-10-21 282 views
0

我想要更改线条宽度,但为什么画布中的所有线条宽度也会发生更改?如何在html5画布中为自定义线条制作线条宽度

贝娄是我的代码片段

let c_canvas = document.getElementById("c"); 
 
let context = c_canvas.getContext("2d"); 
 
let gradientFill = context.createLinearGradient(400, 0, 95, 305); 
 
gradientFill.addColorStop(0, "rgba(195, 42, 28, 1.000)"); 
 
gradientFill.addColorStop(0.6, "rgba(252, 239, 55, 1.000)"); 
 
gradientFill.addColorStop(1, "rgba(12, 151, 206, 1.000)"); 
 
context.fillStyle = gradientFill; 
 
context.fillRect(0, 0, 500, 500); 
 
    context.beginPath(); 
 
for (let x = 0.5; x <= 501; x += 100) { 
 
    context.moveTo(x, 0); 
 
    context.lineTo(x, 500); 
 

 
} 
 

 
for (let y = 0.5; y <= 501; y += 100) { 
 
    context.moveTo(0, y); 
 
    context.lineTo(500, y); 
 
} 
 

 
    context.lineWidth = 1; 
 
    context.stroke(); // Draw it 
 
    
 
let frectx = 100; 
 
let frecty = 450; 
 
let lrectx = 250; 
 
let lrecty = 340; 
 
let radius = 15; // for example 
 
let font = "bold " + radius + "px serif"; 
 
let text = "1"; 
 
let rand =[]; 
 
for(let i=0; i<5; i++) 
 
{ 
 
rand[i] = Math.floor((Math.random() * 6) + 1); 
 

 
} 
 

 
rand.forEach(function(entry,i) { 
 
text = i+1; 
 
frectx = entry*70; 
 
frecty = Math.floor((Math.random() * 9) + 1)*50; 
 

 
context.moveTo(frectx, frecty); 
 
context.lineTo(lrectx, lrecty); 
 
    context.lineWidth = 8; 
 

 
context.strokeStyle = "#ddd"; 
 
context.stroke(); 
 
context.fillStyle = "white"; 
 

 
context.beginPath(); 
 
context.arc(frectx, frecty, 10, 0, 2 * Math.PI); 
 
context.stroke(); 
 
context.closePath(); 
 
context.fill(); 
 
context.fillStyle = "black"; // font color to write the text with 
 

 
context.font = font; 
 
context.textBaseline = "top"; 
 
context.fillText(text, frectx - radius/4, frecty - radius/2); 
 

 
context.fillStyle = "white"; 
 

 
context.beginPath(); 
 
context.arc(lrectx, lrecty, 10, 0, 2 * Math.PI); 
 
context.stroke(); 
 
context.closePath(); 
 
context.fill(); 
 
context.fillStyle = "black"; // font color to write the text with 
 
context.font = font; 
 
context.textBaseline = "top"; 
 
context.fillText(text, lrectx - radius/4, lrecty - radius/2); 
 
})
<canvas id="c" width="501px" height="501px"></canvas>

,或者你可以的jsfiddle看到:

https://jsfiddle.net/dyaskur/t4fgLs73/

如何只改变宽度在箱体内部的线路?

我的第二个问题是如何让我的线条和圆形变换发光/改变颜色时,我徘徊它?

+0

当您开始绘制别的东西时,您需要调用'.... beginPath()'。这里是一个例子:https://jsfiddle.net/muj2fezv/ – Titus

回答

0

一个context.beginPath()

之间

context.lineWidth = 1; 
context.stroke(); // Draw it 

context.lineTo(lrectx, lrecty); 
    context.lineWidth = 8; 

context.strokeStyle = "#ddd"; 
context.stroke(); 
失踪没有 beginPath叫你只是重新抚着全部或路径和子路径已经与新的笔触样式和宽度定义。

问题的第二部分的一般答案是,你不会这样做。

绘画画布相当于绘制图像。您可以计算出鼠标位于图像上的位置,但是如果鼠标移过要更改的某些像素,并且重新绘制画布(如果是),则需要解决(在您的程序中)。

如果您想使用CSS类伪造类来更改表示,您需要为图形构建SVG元素的源代码,从源代码生成元素并为SVG元素的子元素提供适当的CSS将受鼠标位置影响的节点。