我目前正在开发一个Javascript Canvas项目(以前从未编写过Js或之前使用的画布),需要一些关于在画布中心绘制带边框的图像的帮助。
我目前有一个Person.js,其中绘制了人物的矩形和图像:
var Person = (function () {
function Person(pName, pImageUrl) {
this.setId(Person.sTotalNodes++);
this.setName(pName);
this.mImage = new Image();
this.setImageUrl(pImageUrl);
this.mPartners = new Array();
}
Person.sTotalNodes = 0;
Person.prototype.getId = function () {
return this.mId;
};
Person.prototype.setId = function (pId) {
this.mId = pId;
};
Person.prototype.draw = function (context) {
//draw rectangle
var c = document.getElementById("canvas");
context.translate(canvas.width * 0.5, canvas.height * 0.5);
var context = c.getContext("2d");
context.rect(0,0,160,210);
context.fillStyle = '#0073E6';
context.fill();
context.stroke();
//get image and draw
context.drawImage(this.getImage(), 0, 0);
};
Person.prototype.setName = function (pName) {
this.mName = pName;
};
Person.prototype.getName = function () {
return this.mName;
};
Person.prototype.setImageUrl = function (pImageUrl) {
this.mImageUrl = pImageUrl;
this.mImage.src = pImageUrl;
};
Person.prototype.getImageUrl = function () {
return this.mImageUrl;
};
Person.prototype.getImage = function () {
/* when you first get this it will not return a proper image
you need to use the getImageUrl function and then build a new image */
return this.mImage;
};
Person.prototype.getPartner = function (pIndex) {
return this.mPartners[pIndex];
};
Person.prototype.numPartners = function () {
return this.mPartners.length;
};
Person.prototype.addPartner = function (pPartner) {
this.mPartners.push(pPartner);
};
return Person;
})();
但是一旦我添加context.translate(canvas.width * 0.5, canvas.height * 0.5);
以便将原点放在画布的中心,只有矩形绘制?我的任务是什么? (还尝试将context.translate
放在我的main.js中,其中topPerson.draw(context);
被调用以从树中抽取第一个人。
main.js(我称之为树的第一人称)
// add the onLoad event listener to initialise our canvas
if(window.addEventListener) {
window.addEventListener('load', onLoad, true);
}
function onLoad() {
var canvas;
var context;
var exampleFamilyTrees;
var topPerson;
var previousMousePosition;
function initialise() {
canvas = document.getElementById('canvas');
if (!canvas) {
alert('Error: Canvas element not found');
return;
}
context = canvas.getContext('2d');
if (!context) {
alert('Error: Unable to get canvas context');
return;
}
exampleFamilyTrees = new ExampleFamilyTrees();
topPerson = exampleFamilyTrees.getFamilyTree(0);
}
function draw(){
context.translate(canvas.width * 0.5, canvas.height * 0.5);
topPerson.draw(context);
}
function update(){
}
function animationLoop(){
update();
draw();
requestAnimationFrame(animationLoop);
}
initialise();
animationLoop();
}
答案 0 :(得分:0)
您必须在translate
context.rect