我试图画一个"立方体"在画布平面上,使用矢量坐标,我可以绘制2个正方形但是将它们与翻译函数内的4行连接起来似乎不能用于我无法理解的原因。任何建议或帮助表示赞赏。这是一个js bin http://jsbin.com/rozelenocu/1/edit?html,js,output
function Vector(x, y){
this.x = x;
this.y = y;
}
Vector.prototype.plot = function(other){
return new Vector(this.x + other.x, this.y + other.y);
}
var c = document.getElementById("c");
var ctx = c.getContext("2d");
function cube(pos, size, z){
var s1 = square(pos, size);
var s2 = square(pos + z, size);
translate(s1, s2);
}
function square(pos, size){
var shape = [];
shape.push(new Vector(pos + size, pos));
shape.push(new Vector(pos + size, pos + size));
shape.push(new Vector(pos, pos + size));
shape.push(new Vector(pos, pos));
ctx.beginPath();
var line = 0;
ctx.moveTo(pos, pos);
while(line < shape.length) {
ctx.lineTo(shape[line].x, shape[line].y);
console.log(shape[line].x);
line++;
}
ctx.stroke();
return shape;
}
function translate(arr1, arr2) {
ctx.beginPath();
arr1.forEach(function(_, i){
console.log(i);
ctx.moveTo(arr1[i].x, arr1[i].y);
ctx.lineTo(arr2[i].x, arr2[i].y);
});
ctx.closePath();
}
cube(50, 20, 10);
答案 0 :(得分:0)
导致问题的是ctx.closepath。我把它改成了ctx.stroke()