所以我有画布。我想要画出多个填充不同颜色的矩形。
实际的代码非常长,并且有多层依赖关系。以下是有关部分:
var c=document.getElementById("result"); //result is a canvas object
var cnv=c.getContext("2d");
cnv.beginPath();
cnv.strokeStyle="#00F000"; //coloring it green
cnv.moveTo(x,y); //moving to a specific point on the canvas
cnv.fillRect(x,y,3,33); //drawing a filled rectangle
cnv.stroke();
cnv.closePath();如果我警告(cnv.strokeStyle);它确实显示该颜色已设置为00F000,并且它也在绘制矩形。唯一的问题是所有的图纸都是默认(黑色)颜色。
我在这里做错什么了?
发布于 2021-08-05 13:46:42
使用fillStyle代替。
var c=document.getElementById("result"); //result is a canvas object
var cnv=c.getContext("2d");
cnv.beginPath();
cnv.fillStyle="#00F000"; //coloring it green
cnv.moveTo(x,y); //moving to a specific point on the canvas
cnv.fillRect(x,y,3,33); //drawing a filled rectangle
cnv.closePath();发布于 2021-08-05 13:57:17
CanvasRenderingContext2D fillRect()方法通过使用fillStyle方法定义的颜色填充区域。
然而,stroke()方法填充了以前对moveTo()、lineTo()、curveTo()调用定义的路径的轮廓.使用strokeStyle()方法设置的颜色。
在您的代码片段中,没有实际的路径定义,所以对stroke()的最后调用没有结果,唯一的可视输出是对fillRect()的默认黑色的调用。
如果希望矩形的轮廓也可见,则必须使用与fillRect()相同的参数调用fillRect()。
下面是一个例子:
var c=document.getElementById("result"); //result is a canvas object
var cnv=c.getContext("2d");
let x=20;
let y=20;
cnv.beginPath();
cnv.strokeStyle="#00F000"; //coloring it green
cnv.moveTo(x,y); //moving to a specific point on the canvas
cnv.fillRect(x,y,3,33); //drawing a filled rectangle
cnv.strokeRect(x,y,3,33);
cnv.closePath();<canvas id="result"></canvas>
发布于 2021-08-05 14:04:46
如果您想要一个经过抚摸的矩形副(填充的),那么您必须使用strokeRect()而不是fillRect()。另外,这两种方法都允许您不必在之后调用fill()或stroke(),因为它们已经这样做了。
如果要使用cnv.rect(),则需要在之后调用笔画或填充。在编写代码时,一定不要混淆使用strokeRect()和fillRect()。
此外,您也不需要在这些方法中使用moveTo()。它们已经具有所需的x和y值输入。最后,矩形不需要beginPath()和closePath(),因为这已经包含了这一点。
var c=document.getElementById("result");
var cnv=c.getContext("2d");
cnv.strokeStyle="#00F000"; //coloring it green
cnv.strokeRect(20,20,30,33); //drawing a filled rectangle<canvas id='result'></canvas>
你也可以这样做
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d")
ctx.strokeStyle = "purple"
ctx.fillStyle = "lightgreen"
ctx.rect(20, 20, 50, 50)
ctx.fill()
ctx.stroke()<canvas id="canvas"></canvas>
https://stackoverflow.com/questions/68667729
复制相似问题