canvas简单动画

110 阅读1分钟

291891492291361822022-12-16-10-52-18.gif

canvas如何实现,小球按照既定轨道走动呢:

    <canvas
    id="co2Canvas"
    class="co2Canvas"
    ></canvas>
    <canvas
        id="circleCanvas1"
        class="circleCanvas1"
    ></canvas>

以上是canvas元素定义。

    onMounted(() => {
        var c = document.getElementById("co2Canvas");
        c.setAttribute("width", handlePx(800) + "px");
        c.setAttribute("height", handlePx(300) + "px");
        var ctx = c.getContext("2d");
        ctx.moveTo(handlePx(20), handlePx(120));
        ctx.lineTo(handlePx(110), handlePx(120));
        ctx.lineTo(handlePx(173), handlePx(173));
        ctx.lineWidth = 1;
        ctx.strokeStyle = "rgba(247, 230, 205, 0.4)";
        ctx.setLineDash([handlePx(2), handlePx(3)]);
        ctx.stroke();
    });

以上是在画折线,指定了线为虚线、灰色。

    let point1p = {}; // x 初始位置
    let uniformSpeed = 1;
    function circleMove(circtx) {
        window.requestAnimationFrame(() => {
            //这是一个循环执行的方法
            circleMove(circtx);
        });
        circtx.clearRect(0, 0, 800, 300);
        circtx.fillStyle = "#FFDEB4";
        circtx.shadowOffsetX = 0;
        circtx.shadowOffsetY = 0;
        circtx.shadowColor = "#ffffff";
        circtx.shadowBlur = 10;
        drawCircle(circtx, 3); //画实体圆
        getPath(
            { x: handlePx(173), y: handlePx(173) },
            { x: handlePx(110), y: handlePx(120) },
            { x: handlePx(20), y: handlePx(120) }
        );
    }

    // 画实体圆(小球)
    function drawCircle(circtx, radius) {//radius是半径
        // circtx.save();
        circtx.beginPath();
        circtx.arc(point1p.x, point1p.y, radius, 0, Math.PI * 2);
        circtx.closePath();
        circtx.fill();
        // circtx.restore();
    }
    //不断改变 x y坐标
    function getPath(startp, middlep, endp) {
        if (point1p.x > middlep.x && point1p.x <= startp.x) {
            point1p.x = point1p.x - 1;//改变
            point1p.y =
                point1p.y -
                (1 * (middlep.y - startp.y)) / (middlep.x - startp.x);
        }
        if (point1p.x > endp.x && point1p.x <= middlep.x) {
            point1p.x = point1p.x - 1;
            point1p.y =
                point1p.y -
                (1 * (endp.y - middlep.y)) / (endp.x - middlep.x);
        }
        if (point1p.x == endp.x) {
            point1p = startp;
        }
    }

      onMounted(() => {
        var circ = document.getElementById("circleCanvas1");
        circ.setAttribute("width", handlePx(800) + "px");
        circ.setAttribute("height", handlePx(300) + "px");
        var circtx = circ.getContext("2d");
        point1p = { x: handlePx(173), y: handlePx(173) };//定义
        circleMove(circtx);
    })

以上是实体小球按照轨道运行的代码。