JSFiddle - React, Tailwind, and code Playground
ship rotation without context.rotate()
by greg gorlen
HTML
<canvas id="paper" width=600 height=400></canvas>
CSS
body {
background: #000;
display: flex;
align-items: center;
justify-content: center;
width: 100vw;
height: 100vh;
margin: 0;
}
#paper {
border: 1px solid #999;
background: #000;
box-shadow: 0px 3px 8px 3px rgba(255, 255, 255, 0);
}
JavaScript
// Fixing key delay issue: https://stackoverflow.com/questions/3691461/remove-key-press-delay-in-javascript
"use strict";
let canvas = document.getElementById('paper');
let ctx = canvas.getContext('2d');
let ship;
let Ship = function (x, y) {
const MAX_VEL = 4;
const ROTATION_SPEED = 4;
this.x = x;
this.y = y;
this.ax = 0;
this.ay = 0;
this.vx = 0;
this.vy = 0;
this.angle = 0;
this.size = 20;
this.rotatingCW = false;
this.rotatingCCW = false;
this.accelerate = function (speed) {
this.ax += speed;
this.ay += speed;
this.vx += this.ax * Math.cos(degToRad(this.angle));
this.vy += this.ay * Math.sin(degToRad(this.angle));
if (this.vx > MAX_VEL) { this.vx = MAX_VEL; }
else if (this.vx < -MAX_VEL) { this.vx = -MAX_VEL; }
if (this.vy > MAX_VEL) { this.vy = MAX_VEL; }
else if (this.vy < -MAX_VEL) { this.vy = -MAX_VEL; }
};
this.rotateCW = function () {
this.angle += ROTATION_SPEED;
if (this.angle > 180) { this.angle -= 360; }
};
this.rotateCCW = function () {
this.angle -= ROTATION_SPEED;
if (this.angle < -180) { this.angle += 360; }
};
this.move = function () {
if (this.rotatingCCW) { this.rotateCCW(); }
else if (this.rotatingCW) { this.rotateCW(); }
this.x += this.vx;
this.y += this.vy;
if (this.x - this.size > canvas.width) {
this.x = -this.size;
}
else if (this.x + this.size < 0) {
this.x = canvas.width + this.size;
}
if (this.y - this.size > canvas.height) {
this.y = -this.size;
}
else if (this.y + this.size < 0) {
this.y = canvas.height + this.size;
}
}
this.draw = function (ctx) {
let cx = Math.cos(degToRad(this.angle));
let sy = Math.sin(degToRad(this.angle));
ctx.strokeStyle = "#fff";
ctx.fillStyle = "#fff";
ctx.beginPath();
ctx.moveTo(this.x + -this.size / 3 * cx,
this.y + -this.size / 3 * sy);
...