我不知道如何为变量分配坐标,因此我为长度和高度创建了两个坐标,然后分别用height / width变量替换了(0,0)。然后,我使用moveTo和lineTo尝试通过向变量坐标添加+50或-50(px),在变量坐标点周围绘制一个正方形,但未绘制任何内容。在这种情况下,如何在坐标点1(P1W,P1H)上绘制一个正方形?
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
var canvas = document.getElementById("myCanvas");
var WIDTH = canvas.width;
var HEIGHT = canvas.height;
var P1H = HEIGHT/4*1
var P1W = WIDTH/4*1
var P2H = HEIGHT/4*2
var P2W = WIDTH/4*2
var P3H = HEIGHT/4*3
var P3W = WIDTH/4*3
var P4H = HEIGHT/4*4
var P4W = WIDTH/4*4
var SqP1 = ctx.moveTo(P1W-50,P1H+50);
var SqP2 = ctx.moveTo(P1W+50,P1H+50);
var SqP3 = ctx.moveTo(P1W-50,P1H-50);
var SqP4 = ctx.moveTo(P1W+50,P1H-50);
function draw() {
SqP1;
ctx.lineTo(P1W+50,P1H+50);
SqP2;
ctx.lineTo(P1W-50,P1H-50);
SqP3;
ctx.lineTo(P1W+50,P1H-50);
SqP4;
ctx.lineTo(P1W-50,P1H+50);
}
if (1===1) {
draw();
}
console.log(WIDTH);
console.log(HEIGHT);
html {
background-color:#0d3677;
}
html,head {
width: 100%;
height: 100%;
margin: 0px;
}
<canvas id="myCanvas"></canvas>
答案 0 :(得分:0)
一旦移动并绘制线,最后一条语句就必须是ctx.stroke();。我从左上方-右上方-右下方-左下方-左上方绘制了正方形。我还标记了正方形的中心。希望这会有所帮助。
<canvas id="myCanvas"></canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
var canvas = document.getElementById("myCanvas");
var WIDTH = canvas.width;
var HEIGHT = canvas.height;
var P1H = HEIGHT/4*1;
var P1W = WIDTH/4*1;
console.log(P1H +" , " + P1W);
// var P2H = HEIGHT/4*2;
// var P2W = WIDTH/4*2;
//
// var P3H = HEIGHT/4*3;
// var P3W = WIDTH/4*3;
//
// var P4H = HEIGHT/4*4;
// var P4W = WIDTH/4*4;
//
// var SqP1 = ctx.moveTo(P1W-50,P1H+50);
// var SqP2 = ctx.moveTo(P1W+50,P1H+50);
// var SqP3 = ctx.moveTo(P1W-50,P1H-50);
// var SqP4 = ctx.moveTo(P1W+50,P1H-50);
function draw() {
ctx.fillRect(P1W,P1H,1,1); // fill in the pixel at (P1W,P1H)
ctx.moveTo(P1W-50,P1H-50);
ctx.lineTo(P1W+50,P1H-50);
ctx.lineTo(P1W+50,P1H+50);
ctx.lineTo(P1W-50,P1H+50);
ctx.lineTo(P1W-50,P1H-50);
ctx.stroke();
}
if (1===1) {
draw();
}
console.log(WIDTH);
console.log(HEIGHT);
</script>