requestAnimationFrame почему по разному вращает рисунок и примитив
user355286 любезно помог решить задачу плавного вращения окружности с секторами. Добавил еще один canvas1 c рисунком...ничего больше не изменял...вращает на разные углы, хотел на Math.PI/3: окружность это делает, рисунок как заведенный на 2n * Math.PI + Math.PI/3! Почему, вот код:
<script type="text/javascript">
let context = canvas.getContext("2d")
let ctx1 = canvas1.getContext("2d")
let w, h
let circle = {x: 0, y: 0, r: 0, a: 0}
let frame_id, start_time, dir
let dest = Math.PI/3, cur = 0, dur = 2
let myImage = new Image();
function drawImg() {//рисунок
myImage.crossOrigin = true;
myImage.src = 'https://picsum.photos/300/150';
myImage.onload = function(){
clear(ctx1);
ctx1.drawImage(myImage,0,0,300,300);
}
}
drawImg()
function drawCircle() {//окружность с секторами вращается нормально
context.beginPath()
context.lineWidth = (w+h)/2*0.01
context.arc(circle.x, circle.y, circle.r, 0, Math.PI * 2)
context.stroke()
context.lineWidth = (w+h)/2*0.005
for (let i = 0; i < Math.PI * 2; i += Math.PI / 10) {
const x2 = circle.x + circle.r * Math.cos(i)
const y2 = circle.y + circle.r * Math.sin(i)
line(circle.x, circle.y, x2, y2)
}
function line(x1, y1, x2, y2) {
context.beginPath()
context.moveTo(x1, y1)
context.lineTo(x2, y2)
context.stroke()
}
}
function clear(abc) {
abc.clearRect(0, 0, w, h)
}
function easeInOutQuint(t) {
return t < .5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t
}
function update() {
clear(context)
let t = Date.now() - start_time
t /= 1000 * dur
if (t <= 1) frame_id = requestAnimationFrame(update)
t = easeInOutQuint(t)
cur = dest * Math.min(t, 1) * dir
rotate(cur)
rotate1(cur)
}
function rotate1(angle) {
context.save()
context.translate(circle.x, circle.y)
context.rotate(circle.a + angle)//при клике handleClick(e):cur = 0;
//circle.a = circle.a + cur
//angle = cur
//cur = dest * Math.min(t, 1) * dir
context.translate(-circle.x, -circle.y)
drawCircle()
context.restore()
}
function rotate(angle) {
ctx1.save()
ctx1.translate(circle.x, circle.y)
ctx1.rotate(circle.a + angle)
ctx1.translate(-circle.x, -circle.y)
drawImg()
}
function handleResize() {
w = canvas.width
h = canvas.height
circle.r = Math.min(w, h) / 2 * 0.6
circle.x = w / 2
circle.y = h / 2
drawCircle()
drawImg()
}
function handleClick(e) {
if (e.x > 0 && e.x < w / 2) dir = -1
if (e.x > w / 2 && e.x < w) dir = 1
cur = 0
circle.a += cur //circle.a = circle.a + cur
start_time = Date.now()
cancelAnimationFrame(frame_id)
frame_id = requestAnimationFrame(update)
}
window.addEventListener("click", handleClick)
window.addEventListener("resize", handleResize)
</script>
#canvas {float: left;
border:2px solid red;
}
#canvas1 {
float: left;
border: 2px solid blue;
}
<canvas id="canvas" width="300" height="300"></canvas>
<canvas id="canvas1" width="300" height="300"></canvas>