admin管理员组

文章数量:1399965

I'm trying to draw two rectangles of different colors:

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.beginPath();
context.drawImage(this,0,0);
context.beginPath();
context.rect(left1,top1,width1,height1);
context.lineWidth = 8;
context.strokeStyle = 'red';
context.stroke();
context.rect(left2,top2,width2,height2);
context.lineWidth = 8;
context.strokeStyle = 'green';
context.stroke();

But both e out the same color (green, which is the second color chosen).

I guess that stroke doesn't do what I expect it to do.

What am I missing here?

I'm trying to draw two rectangles of different colors:

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.beginPath();
context.drawImage(this,0,0);
context.beginPath();
context.rect(left1,top1,width1,height1);
context.lineWidth = 8;
context.strokeStyle = 'red';
context.stroke();
context.rect(left2,top2,width2,height2);
context.lineWidth = 8;
context.strokeStyle = 'green';
context.stroke();

But both e out the same color (green, which is the second color chosen).

I guess that stroke doesn't do what I expect it to do.

What am I missing here?

Share Improve this question edited Jan 6, 2021 at 20:03 halfer 20.4k19 gold badges109 silver badges202 bronze badges asked Oct 15, 2017 at 20:20 goodvibrationgoodvibration 6,2164 gold badges34 silver badges69 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

The trick is that you simply need to call context.beginPath() before creating the second square.

Although not strictly needed, you should also pletely close your paths with context.closePath() as well (which is called before context.stroke()).

I've added both context.beginPath() and context.closePath() to the following example:

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
//context.beginPath();
//context.drawImage(this, 0, 0);
context.beginPath();
context.rect(30, 30, 30, 30); /* Modified */
context.lineWidth = 8;
context.strokeStyle = 'red';
context.closePath();
context.stroke();
context.beginPath(); /* Added */
context.rect(80, 30, 30, 30); /* Modified */
context.lineWidth = 8;
context.strokeStyle = 'green';
context.closePath();
context.stroke();
<canvas id="canvas" width="150" height="100" style="border:1px solid #000000;">
</canvas>

Hope this helps! :)

Look at this example

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

// Red rectangle
ctx.beginPath();
ctx.lineWidth = "6";
ctx.strokeStyle = "red";
ctx.rect(5, 5, 290, 140); 
ctx.stroke();

// Green rectangle
ctx.beginPath();
ctx.lineWidth = "4";
ctx.strokeStyle = "green";
ctx.rect(30, 30, 50, 50);
ctx.stroke();
<canvas id="myCanvas" width="300" height="150">

本文标签: javascriptDraw on canvas rectangles of different colorsStack Overflow