q1: 是否可以有一个不可见的矩形?
q2: 是否可以在方法上调用方法?见下文。
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "";
ctx.strokeStyle = "";
// as far FF 3.67 goes, no way
// the goal is to fill the rectangle with some text
ctx.fillRect(50,50,50,20).fillText("you rock",250,250);
谢谢。
最佳答案
q1:是否可以有一个不可见的矩形?
确实是这样!
ctx.fillStyle = 'rgba(255,255,255,0)';
ctx.fillRect(50,50,50,20);
虽然这也有效,而且更简洁:
;
q2:是否可以在方法上调用方法?
可以想象你可以做这样的事情:
//Naive generic chainer function
//returns this even if the default
//value is significant!
function chain(obj) {
function F() {}
F.prototype = obj;
var cobj = new F();
for (var i in obj) {
if (typeof obj[i] == 'function') {
//Function Bind-ish
cobj[i] = (function() {
var method = i;
return function() {
this.constructor.prototype[method].apply(this, arguments);
return this;
};
}());
}
}
return cobj;
}
var chained = chain(ctx);
chained.fillRect(0,0,200,200)
.fillRect(100,100,200,200)
.fillRect(400,400,100,100)
.fillText("I CAN HAS INVISDIBLE??", 250, 250);
但是当你可以做到这一点时为什么还要麻烦呢:
with (ctx) {
fillRect(100,100,200,200);
fillRect(300,300,100,100);
fillStyle = 'green'; //I CAN SEE
fillText("SCREW BEST PRACTICES");
}
关于HTML5 Canvas 挑战!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3314162/