goo*_*ion 3 html javascript canvas
我正在尝试绘制两个不同颜色的矩形:
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();
Run Code Online (Sandbox Code Playgroud)
但两者的颜色相同(绿色,这是选择的第二种颜色)。
我想这stroke并没有达到我预期的效果。
我在这里缺少什么?
诀窍是您只需要context.beginPath()在创建第二个方块之前调用即可。
虽然不是严格需要,但您也应该完全关闭您的路径(之前context.closePath()称为)。 context.stroke()
我已将context.beginPath()和添加context.closePath()到以下示例中:
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();Run Code Online (Sandbox Code Playgroud)
<canvas id="canvas" width="150" height="100" style="border:1px solid #000000;">
</canvas>Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!:)