讓您的代碼編譯出現幾個問題。檢查javascript控制檯以查找任何javascript錯誤。我已經爲bud對象添加了init方法。一旦編譯完成,你就不遠了。
使用one.draw(bud.x,bud.y,120);
繪製和ctx.drawImage(image, -(w/2), -h,w,h);
定位的東西在正確的地方。
一個完整的工作的例子是:
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 500;
var TO_RADIANS = Math.PI/180;
var bud = {
size:15,
init : function() {
this.x = (canvas.width-this.size)/2;
this.y = (canvas.height-this.size)/2;
},
draw: function(){
console.log("bud,draw",this.x,this.y,this.size);
drawCircle(this.x,this.y,this.size);
}
}
function Petal(){
this.w = bud.size*3.5;
this.h = bud.size*3.5;
this.img = new Image();
this.img.src = "http://i.imgur.com/BMeZIvV.jpg";
this.draw = function(middleX,middleY,angle){
drawRotatedImage(this.img,middleX,middleY,this.w,this.h,angle);
}
}
bud.init();
var one = new Petal();
one.draw(bud.x,bud.y,120);
one.draw(bud.x,bud.y,-120);
one.draw(bud.x,bud.y,0);
bud.draw();
function drawCircle(x,y,size){
ctx.fillStyle = "green";
ctx.beginPath();
ctx.arc(x,y,size,0,2*Math.PI);
ctx.fill();
}
function drawRotatedImage(image, x, y, w, h, angle) {
console.log("drawRotatedImage",x,y,w,h,angle);
// save the current co-ordinate system
// before we screw with it
ctx.save();
// move to the middle of where we want to draw our image
ctx.translate(x, y);
// rotate around that point, converting our
// angle from degrees to radians
ctx.rotate(angle * TO_RADIANS);
// draw it up and to the left by half the width
// and height of the image
ctx.drawImage(image, -(w/2), -h,w,h);
// and restore the co-ords to how they were when we began
ctx.restore();
}
您的代碼只顯示一個沒有花瓣的綠色圓圈。我發給你一個過時的鏈接btw。我不知道如何,但我是在那個小提琴的第六個版本,而不是第三個。我的帖子中的代碼也不在示例中。 這是新鏈接:https://jsfiddle.net/b90mbrkg/6/ – onlyme0349
Math.atan2(bud.x- x, - (bud.y- y))*(180/Math.PI))這是我需要的公式。 – onlyme0349
我認爲延遲加載圖像存在問題。您需要運行程序兩次才能加載圖像。嘗試使用'img.addEventListener(「load」,function(){}'。http和https混合內容也有問題。如果你對轉換很聰明,你不需要atan2部分。然後畫出花瓣相對於這個中心,在平移和旋轉之後,原點位於花蕾的中心,通過將圖像放在'ctx.drawImage(image, - (w/2),-h ,w,h);'這將花瓣的尖端放在花蕾的中心 –