gpt4 book ai didi

javascript - 为什么我的 HTML Canvas 不旋转?

转载 作者:行者123 更新时间:2023-12-02 15:58:32 25 4
gpt4 key购买 nike

Canvas 脚本:

function clock_hand_hh(hh) {
var hh_canvas = document.getElementById('clock_hand_hh');
var hh_context = hh_canvas.getContext('2d');
hh_canvas.width = 500;
hh_canvas.height = 500;
var centerX = hh_canvas.width / 2;
var centerY = hh_canvas.height / 2;
var radius = 10;

hh_context.beginPath();
hh_context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
hh_context.fillStyle = '#000000';
hh_context.fill();
hh_context.lineWidth = 5;
hh_context.strokeStyle = '#000000';
hh_context.stroke();

hh_context.beginPath();
hh_context.bezierCurveTo(centerX, centerY, centerX - 10, centerY - 50, centerX, centerY - 100);
hh_context.bezierCurveTo(centerX, centerY-100, centerX + 10, centerY - 50, centerX, centerY);
hh_context.fillStyle = '#000000';
hh_context.fill();
hh_context.lineWidth = 2;
hh_context.strokeStyle = '#000000';
hh_context.stroke();

if (hh > 12) {
hh = hh - 12;
}
//alert((hh / 12) * 2 * Math.PI);
hh_context.translate(centerX, centerY);
hh_context.rotate((hh / 12) * 2 * Math.PI);
}

注意:警报(我评论过)显示 Canvas 所需的正确旋转 Angular 值(以弧度为单位)。

最佳答案

您只需移动它两次:使用center变量进行绘制,然后也移动坐标...

    function clock_hand_hh(hh) {
var hh_canvas = document.getElementById('clock_hand_hh');
var hh_context = hh_canvas.getContext('2d');
hh_canvas.width = 500;
hh_canvas.height = 500;
var centerX = hh_canvas.width / 2;
var centerY = hh_canvas.height / 2;
var radius = 10;

hh_context.translate(centerX, centerY);
hh_context.rotate((hh / 12) * 2 * Math.PI);

hh_context.beginPath();
hh_context.arc(0, 0, radius, 0, 2 * Math.PI, false);
hh_context.fillStyle = '#000000';
hh_context.fill();
hh_context.lineWidth = 5;
hh_context.strokeStyle = '#000000';
hh_context.stroke();


hh_context.beginPath();
hh_context.bezierCurveTo(0, 0, -10, -50, 0, -100);
hh_context.bezierCurveTo(0, -100, 10, -50, 0, 0);
hh_context.fillStyle = '#000000';
hh_context.fill();
hh_context.lineWidth = 2;
hh_context.strokeStyle = '#000000';
hh_context.stroke();

if (hh > 12) {
hh = hh % 12 + 1;
}
//alert((hh / 12) * 2 * Math.PI);
}

clock_hand_hh(4);
<canvas id="clock_hand_hh" style="width: 200px; height: 200px;"></canvas>

关于javascript - 为什么我的 HTML Canvas 不旋转?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31398501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com