html5 cube,javascript - html5 canvas correctly draw a cube - Stack Overflow

I'm just trying out HTML5 canvas and I'm trying to correctly draw an isometric cube

Here's my current code to draw an isometric cube:

function drawCube(x, y, wx, wy, h, color) {

// left face

ctx.beginPath();

ctx.moveTo(x, y);

ctx.lineTo(x - wx, y - wx * 0.5);

ctx.lineTo(x - wx, y - h - wx * 0.5);

ctx.lineTo(x, y - h * 1);

ctx.closePath();

ctx.fillStyle = "#838357"

ctx.strokeStyle = "#7a7a51";

ctx.stroke();

ctx.fill();

// right face

ctx.beginPath();

ctx.moveTo(x, y);

ctx.lineTo(x + wy, y - wy * 0.5);

ctx.lineTo(x + wy, y - h - wy * 0.5);

ctx.lineTo(x, y - h * 1);

ctx.closePath();

ctx.fillStyle = "#6f6f49";

ctx.strokeStyle = "#676744";

ctx.stroke();

ctx.fill();

// center face

ctx.beginPath();

ctx.moveTo(x, y - h);

ctx.lineTo(x - wx, y - h - wx * 0.5);

ctx.lineTo(x - wx + wy, y - h - (wx * 0.5 + wy * 0.5));

ctx.lineTo(x + wy, y - h - wy * 0.5);

ctx.closePath();

ctx.fillStyle = "#989865";

ctx.strokeStyle = "#8e8e5e";

ctx.stroke();

ctx.fill();

}

I have two problems with this:

First issue

There's some pixel issues/faces are overlapping that you can see when you scale the canvas:

b6B3P.png

var canvas = document.createElement("canvas");

var ctx = canvas.getContext('2d');

canvas.width = 800;

canvas.height = 800;

document.body.appendChild(canvas);

function draw() {

ctx.clearRect(0, 0, canvas.width, canvas.height);

var sizeX = 32;

var sizeY = 32;

var sizeZ = 8;

ctx.scale(5, 5);

drawCube(50, 50, sizeX, sizeY, sizeZ);

}

requestAnimationFrame(draw);

function drawCube(x, y, wx, wy, h, color) {

// left face

ctx.beginPath();

ctx.moveTo(x, y);

ctx.lineTo(x - wx, y - wx * 0.5);

ctx.lineTo(x - wx, y - h - wx * 0.5);

ctx.lineTo(x, y - h * 1);

ctx.closePath();

ctx.fillStyle = "#838357"

ctx.strokeStyle = "#7a7a51";

ctx.stroke();

ctx.fill();

// right face

ctx.beginPath();

ctx.moveTo(x, y);

ctx.lineTo(x + wy, y - wy * 0.5);

ctx.lineTo(x + wy, y - h - wy * 0.5);

ctx.lineTo(x, y - h * 1);

ctx.closePath();

ctx.fillStyle = "#6f6f49";

ctx.strokeStyle = "#676744";

ctx.stroke();

ctx.fill();

// center face

ctx.beginPath();

ctx.moveTo(x, y - h);

ctx.lineTo(x - wx, y - h - wx * 0.5);

ctx.lineTo(x - wx + wy, y - h - (wx * 0.5 + wy * 0.5));

ctx.lineTo(x + wy, y - h - wy * 0.5);

ctx.closePath();

ctx.fillStyle = "#989865";

ctx.strokeStyle = "#8e8e5e";

ctx.stroke();

ctx.fill();

}

Second issue

How can I figure out the required canvas width/height to draw the entire cube, and then set the cube to the beginning of the canvas? (x & y = 0)

What am I doing wrong for the first issue? And what about the second? Could I get an example/snippet with these issues fixed?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值