canvas中如何让图片3d旋转

新手上路,请多包涵

canvas绘制的图片可以平面旋转,如何实现3d旋转呢?

阅读 3.5k
2 个回答

如果就晃简单的旋转,模拟一下还是可以的
效果
https://jsfiddle.net/papersna...

const ctx = canvas.getContext("2d");
var W = canvas.width, H = canvas.height;
const img = new Image;
img.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Flat_tick_icon.svg/1024px-Flat_tick_icon.svg.png";
img.addEventListener("load", () => requestAnimationFrame(renderLoop), {once:true});
function rotateImg(img, axisX, axisY, rotate, centerX, centerY, backCol) {
    const iw = img.naturalWidth/2;
    const ih = img.naturalHeight/2;
    const axisLen = Math.hypot(axisX, axisY);
    const nAx = axisX / axisLen;
    const nAy = axisY / axisLen;
    const wScale = Math.cos(rotate);
    ctx.setTransform(nAy * wScale, -nAx * wScale, nAx, nAy, centerX, centerY);
    ctx.globalAlpha = 1;
    ctx.drawImage(img, -iw * 0.5, -ih * 0.5, iw, ih);
    if (backCol) {
        ctx.globalAlpha = wScale < 0 ? 1 : 1 - wScale;
        ctx.fillStyle = backCol;
        ctx.fillRect(-iw * 0.5, -ih * 0.5, iw, ih);
    }
}
function renderLoop(time) {
    ctx.setTransform(1,0,0,1,0,0);
    ctx.clearRect(0, 0, W, H);
    
    rotateImg(img, Math.cos(time / 4200), Math.sin(time / 4200), time / 500, W * 0.5, H * 0.5, "#268C");
    requestAnimationFrame(renderLoop);

}

不能。3d 旋转得用 3d 绘图引擎。不过你可以直接让整个 canvas 3d 旋转。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进