【发布时间】:2019-01-30 19:18:41
【问题描述】:
过去三周我正在创建一个画布引擎,上周我试图解决一个在画布中旋转对象的问题。我尝试了很多解决方案,但都没有成功。在大多数情况下,代码是旋转画布的全部内容或者它什么都不显示(就像现在一样(但如果你删除 .save() 和 .restore(),一切都会旋转))。我希望这可以避免对代码进行重大更改,因为这是我编写的最大代码(而且我不想做很多更改)。代码 sn-p 在下面,感谢您的帮助。 (想看完整代码可以去here)
//Functions.js File
function degToRad(int) {
return int * Math.PI / 180;
}
//Init.js File
var fps = 0;
var objects = new Array();
var ctx_real = {
context: undefined,
width: 0,
height: 0,
init: function () {
this.context = this.DOM.getContext("2d");
this.width = this.DOM.width;
this.height = this.DOM.height;
},
clear: function () {
this.context.clearRect(0, 0, this.width, this.height);
}
};
const proXy_ctx = {
get: function (target, prop) {
return target.hasOwnProperty(prop) ? target[prop] : ctx_real.context; //=> ctx.SomeAtributeThatNotExists = ctx.context
}
};
const ctx = new Proxy(ctx_real, proXy_ctx);
function init() {
ctx.DOM = document.getElementById("ctx");
ctx.init();
setLayout("Game");
setLayout("Test2");
setInterval(frameUpdate, 1);
}
//Script.js File
async function frameUpdate() {
ctx.clear();
clearObjects = false;
for (var tmp0 = 0 in objects) {
var object = objects[tmp0];
var id = object[0];
var type = object[1];
var x = object[2];
var y = object[3];
var color = object[4];
ctx.context.strokeStyle = color;
ctx.context.fillStyle = color;
var arg0 = object[5];
var arg1 = object[6];
var arg3 = object[8];
var arg4 = object[9];
switch (type) {
case "Rct":
var translateX = x + (arg0 / 2);
var translateY = y + (arg1 / 2);
if (typeof arg3 == "number" && arg3 != 0) {
ctx.context.save();
ctx.context.translate(translateX, translateY);
ctx.context.rotate(degToRad(arg3));
}
if (arg4) {
ctx.context.fillRect(x, y, arg0, arg1);
} else {
ctx.context.strokeRect(x, y, arg0, arg1);
}
if (typeof arg3 == "number") {
ctx.context.restore();
}
break;
}
}
if (clearObjects) {
objects = objects.filter(Boolean);
}
fps++;
setTimeout(function () { fps--; }, 1000);
ctx.context.fillStyle = "black";
ctx.context.font = "10px Verdana";
ctx.context.fillText(fps, 10, 10);
}
function setLayout(layoutName) {
switch (layoutName) {
case "Game":
createObject(["SomeId", "Rct", 0, ctx.height - 30, "green", ctx.width, 30, , , true]);
createObject(["SomeId", "Rct", 0, ctx.height - 30, "#402a25", ctx.width, 3, , , true]);
break;
case "Test2":
createObject(["SomeRotatedEl", "Rct", ctx.width / 2, ctx.height / 2, "red", 50, 50, , 90, true]);
break;
}
}
function createObject(object) {
objects.push(object);
}
html,
body,
canvas {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
overflow-x: hidden;
overflow-y: hidden;
}
<!DOCTYPE html>
<html>
<body onLoad="init()">
<canvas id="ctx">You can simple download e.g. Chrome or what?!!!</canvas>
</body>
</html>
【问题讨论】:
-
您似乎将红色矩形旋转和/或平移出视口。此外,如果您已经翻译了上下文,则需要将绘图坐标(
fillRect)用于该翻译。
标签: javascript canvas